项目中须要用到定时器和循环执行。去网上搜了一下,比较常见的有一下集中。运用Python线程执行轮询操做,也有运用Linux系统的Cron,Celery的文章最多,可是太麻烦。看看就知道,Celery 须要一个发送和接受消息的传输者。RabbitMQ 和 Redis 中间人的消息传输支持全部特性,但也提供大量其余实验性方案的支持,包括用 SQLite 进行本地开发。须要用到队列,对于这点需求简直就是大材小用。最后找到了比较合适的Flask-APScheduler。python
看看 github的flask-apscheduler介绍。git
pip install Flask-APScheduler
在Flask配置文件中添加github
SCHEDULER_API_ENABLED = True JOBS = [ { 'id': 'job_1h_data', 'func': job_1h_data, 'args': '', 'trigger': { 'type': 'cron', 'day_of_week': "0-6", 'hour': '*', 'minute': '1', 'second': '0' } }, { 'id': 'job_announce', 'func': exchange_an, 'args': '', 'trigger': 'interval', 'seconds': 300 } ]
上面指定了每一小时获取全部货币24h最高位以及交易所公告。shell
def exchange_an(): """ :param start_date: 开始时间 YYYY-MM-DD HH:MM:SS :param end_date: 结束时间 YYYY-MM-DD HH:MM:SS :return: 推送消息,保持数据库 """ current_local = time.time() start_date = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(current_local - 300)) end_date = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(current_local)) announce = pro.query('exchange_ann', start_date=start_date, end_date=end_date) print('请求交易所公告...') for x in announce.values: s = { 'title': x[0], 'content': x[1], 'type': x[2], 'url': x[3], 'datetime': x[4] } value = json.dumps(s) print(value) mqttClient.publish('system/ex_announce', value)
# coding:utf-8 from apscheduler.schedulers.blocking import BlockingScheduler import datetime def aps_test(x): print datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), x scheduler = BlockingScheduler() scheduler.add_job(func=aps_test, args=('定时任务',), trigger='cron', second='*/5') scheduler.add_job(func=aps_test, args=('一次性任务',), next_run_time=datetime.datetime.now() + datetime.timedelta(seconds=12)) scheduler.add_job(func=aps_test, args=('循环任务',), trigger='interval', seconds=3, id='interval_task') scheduler.start() """ 暂停任务 """ scheduler.pause_job('interval_task') """ 恢复任务 """ scheduler.resume_job('interval_task') """ 删除任务 """ scheduler.remove_job('interval_task')
apscheduler支持添加三种方式的任务,分别是定时任务,一次性任务及循环任务。同时也包含了对任务的控制。数据库
由于是单机版本,因此指定服务器运行任务,Rest接口管理任务,Rest接口认证就不写了。后续有需求在继续。json
欢迎 长按下图 -> 识别图中二维码或者微信 扫一扫关注个人公众号
![]()