thinkphp5+python.apscheduler實現計劃任務

1.thinkphp5配置自定義命令行php

/application/console/command
namespace app\console\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use app\autotask\task;

class Test extends Command{

    /**
     * 定義命令
     * 命令名稱是 test
     */
    protected function configure()
    {
        $this->setName('test')->setDescription('Here is the market test task ');
    }
    /**
     * 命令執行的內容
     * @param Input $input
     * @param Output $output
     */
    protected function execute(Input $input, Output $output)
    {
        $output->writeln("StartCommand Test:");
        $object = new \app\autotask\task\Test();
        $object->run();
        $output->writeln("End Test..");
    }
}

2.python安裝APScheduler是Python的一個定時任務框架,能夠很方便的知足用戶定時執行或者週期執行任務的需求,它提供了基於日期date、固定時間間隔interval 、以及相似於Linux上的定時任務crontab類型的定時任務。而且該框架不只能夠添加、刪除定時任務,還能夠將任務存儲到數據庫中,實現任務的持久化,因此使用起來很是方便。python

更多瞭解  https://pypi.org/project/APScheduler/thinkphp

pip install apscheduler 
#!/user/bin/env python
#
# -*- coding: UTF-8 -*-

import time
from apscheduler.schedulers.blocking import BlockingScheduler
import logging
import os

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)

fileHandler = logging.FileHandler('./log/task.log', mode='w', encoding='UTF-8')
fileHandler.setLevel(logging.NOTSET)

formatter = logging.Formatter('%(asctime)s - %(message)s')
fileHandler.setFormatter(formatter)

logger.addHandler(fileHandler)

def task():
    output = os.popen('php think test')
    logger.info(output)
    print output.read()

if __name__ == '__main__':
	scheduler = BlockingScheduler()
	scheduler.add_job(task, 'cron', hour='9-22', second = '*/1')
	#scheduler.add_job(task, 'cron', hour='9-22', second = '*/1')
	scheduler.add_job(task, 'cron', hour='9-22', second = '*/1')
	scheduler.add_job(task, 'cron', hour = 22,minute = 1)
	scheduler.add_job(task, 'interval', minutes=1)
	print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))

try:
    scheduler.start()
except (KeyboardInterrupt, SystemExit):
    pass
相關文章
相關標籤/搜索