二、Python Celery 4.4.7 与 Django 2.X的集成【定时任务的调用】

0、这里简单介绍增加定时任务的功能,环境搭建这块,请参考:

1、一、Python Celery 4.4.7 与 Django 2.X的集成【实现异步调用】
https://www.cnblogs.com/ygbh/p/13618556.html

2、Linux RabbitMQ单机与集群部署
https://www.cnblogs.com/ygbh/p/13461525.html

3、Python Celery与RabbitMQ结合操作
https://www.cnblogs.com/ygbh/p/13530885.html

1、首先到GitHub拉取代码

[root@mq1 ~]# git clone git@github.com:ygbh/celery_django_project.git
Cloning into 'celery_django_project'...
remote: Enumerating objects: 33, done.
remote: Counting objects: 100% (33/33), done.
remote: Compressing objects: 100% (23/23), done.
remote: Total 33 (delta 7), reused 27 (delta 6), pack-reused 0
Receiving objects: 100% (33/33), 9.93 KiB | 0 bytes/s, done.
Resolving deltas: 100% (7/7), done.

[root@mq1 ~]# ll

drwxr-xr-x   5 root root  136 Sep  9 16:48 celery_django_project

 2、在tasks.py增加测试定时任务的函数

[root@mq1 celery_django_project]# tail -n 10 app01/tasks.py 
@shared_task(ignore_result=True)  # 生产为:ignore_result=False,自动调度任务,需要配置返回结果关闭,结果没有什么义意,不然数据会越来越多,导致中间件挂掉
def start_cycle_task(arg1, argv):
    """
        这个是测试定时任务的函数
    :param arg1: 传入参数
    :param argv: 传入列表
    :return: 返回'ok'
    """
    print('时间戳:' + str(int(time.time())))
    return 'ok'

 3、在celery_settings.py 增加定时任务的配置

# 配置定时周期的任务
# 参考官方文档:https://docs.celeryproject.org/en/stable/userguide/periodic-tasks.html#available-fields
CELERY_BEAT_SCHEDULE = {
    # test_task1 ==> 'schedule': 3.0,定义几秒即可
    # 'test_task1': {
    #     'task': 'app01.tasks.start_cycle_task',
    #     'schedule': 3.0,
    #     'args': (16, [1, 2, 3])
    # },
    # test_task2 ==> ’crontab()’,设定时期时间,跟Linux的crontab,差不多
    'test_task2': {
        'task': 'app01.tasks.start_cycle_task',
        'schedule': crontab(month_of_year='9', day_of_month='9', minute='*/1'),  # 设置9月9日,每一分钟执行一次
        'args': (16, [1, 2, 3])
    },
}

4、启动服务

1、启动worker服务
[root@mq1 celery_django_project]# celery -A django_celery_project worker -l info

2、启动beat服务
[root@mq1 celery_django_project]# celery beat -A django_celery_project --schedule=/var/run/celery/celerybeat-schedule

5、验证结果,这里的代码是1分钟执行一次

5.1、Worker端显示

5.2、Beat端显示

5.3、Beat端序列化的位置

 

6、定时任务配置完成

原文地址:https://www.cnblogs.com/ygbh/p/13639068.html