本文主要是介绍celery 定时任务demo,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
目录结构:
celery_schedule_demo
├── __init__.py
├── celery_server.py
└── celery_task.py
celery_server.py
# -*- coding: utf-8 -*-
from celery import Celerymyapp = Celery('schedule')
myapp.conf.broker_url = 'redis://localhost:6379/0'
myapp.conf.result_backend = 'redis://localhost:6379/1'
myapp.conf.imports = ['celery_task']
myapp.conf.worker_concurrency = 1myapp.conf.beat_schedule = {# 5秒执行一次demo_schedule任务'every-5s': {'task': 'demo_schedule',# 'schedule': crontab(),'schedule': 5.0,}
}
celery_task.py
# -*- coding: utf-8 -*-
from celery_server import myapp@myapp.task(name='demo_schedule')
def demo():print('demo' * 10)return 'demo'
if __name__ == '__main__':demo.delay()
celery_schedule_demo目录下启动beat
celery -A celery_server.myapp beat -l debug
输出:
celery beat v4.4.7 (cliffs) is starting.
__ - ... __ - _
LocalTime -> 2021-01-05 00:33:23
Configuration ->. broker -> redis://localhost:6379/0. loader -> celery.loaders.app.AppLoader. scheduler -> celery.beat.PersistentScheduler. db -> celerybeat-schedule. logfile -> [stderr]@%DEBUG. maxinterval -> 5.00 minutes (300s)
[2021-01-05 00:33:23,769: DEBUG/MainProcess] Setting default socket timeout to 30
[2021-01-05 00:33:23,769: INFO/MainProcess] beat: Starting...
[2021-01-05 00:33:23,775: DEBUG/MainProcess] Current schedule:
<ScheduleEntry: every-5s demo_schedule() <freq: 5.00 seconds>
[2021-01-05 00:33:23,775: DEBUG/MainProcess] beat: Ticking with max interval->5.00 minutes
[2021-01-05 00:33:23,787: INFO/MainProcess] Scheduler: Sending due task every-5s (demo_schedule)
[2021-01-05 00:33:23,799: DEBUG/MainProcess] beat: Synchronizing schedule...
[2021-01-05 00:33:23,800: DEBUG/MainProcess] demo_schedule sent. id->9c8d08b4-9f4f-4799-9446-d4680cb198cc
[2021-01-05 00:33:23,800: DEBUG/MainProcess] beat: Waking up in 4.97 seconds
然后再开一个终端启动 worker
celery -A celery_server.myapp worker -l
输出:
-------------- celery@bogon v4.4.7 (cliffs)
--- ***** -----
-- ******* ---- Darwin-19.5.0-x86_64-i386-64bit 2021-01-05 00:35:15
- *** --- * ---
- ** ---------- [config]
- ** ---------- .> app: schedule:0x1065b90f0
- ** ---------- .> transport: redis://localhost:6379/0
- ** ---------- .> results: redis://localhost:6379/1
- *** --- * --- .> concurrency: 1 (prefork)
-- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker)
--- ***** ----- -------------- [queues].> celery exchange=celery(direct) key=celery[2021-01-05 00:35:18,180: WARNING/ForkPoolWorker-1] demodemodemodemodemodemodemodemodemodemo
[2021-01-05 00:35:23,141: WARNING/ForkPoolWorker-1] demodemodemodemodemodemodemodemodemodemo
[2021-01-05 00:35:28,142: WARNING/ForkPoolWorker-1] demodemodemodemodemodemodemodemodemodemo
[2021-01-05 00:35:33,140: WARNING/ForkPoolWorker-1] demodemodemodemodemodemodemodemodemodemo
可以看到5秒钟打印一次demodemodemodemodemodemodemodemodemodemo
说明定制任务成功。
这篇关于celery 定时任务demo的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!