django应用内添加有项目/模块关联的定时任务

此文由来

最近项目进入后期测试上线环节,有一个后端任务(定时发送邮件)需要在工作机上定时跑起来,但是此任务不仅需要python虚拟环境,而且邮件生成过程中还会调用项目内的app对模型进行匹配

from django.apps import apps
...
model = next((m for m in apps.get_models() if m._meta.db_table == 'xxxxxx'), None)
...

一般情况下我们会想到使用crontab来设置定时任务

10 10 * * * /bin/bash /home/xxxx/send_mail.sh

(venv) bxxx:~/xxx$ cat send_mail.sh 
#!/bin/bash
cd /home/xxx/ && /home/xxx/venv/bin/python ./xxx/utils/mail/test_send.py
echo 'send over' >> /home/xxx/me.txt

或者用其他方法,比如直接往/etc/crontab写
或者在/etc/cron.d/这个目录下创建任意名称的文件,
这里写图片描述
或者创建*.cron,然后使用

crontab *.cron

但是上边的所有方法发邮件都有问题,并不是说程序没有执行,就是发不出来邮件

echo 'send over' >> /home/xxx/me.txt

最终定位就是因为应用中的引用以及上下文环境问题,最终,解决方法来了

setup
install via pip:

pip install django-crontab
add it to installed apps in django settings.py:

INSTALLED_APPS = (
    'django_crontab',
    ...
)
now create a new method that should be executed by cron every 5 minutes, f.e. in myapp/cron.py:

def my_scheduled_job():
  pass
now add this to your settings.py:

CRONJOBS = [
    ('*/5 * * * *', 'myapp.cron.my_scheduled_job')
]
you can also define positional and keyword arguments which let you call django management commands:

CRONJOBS = [
    ('*/5 * * * *', 'myapp.cron.other_scheduled_job', ['arg1', 'arg2'], {'verbose': 0}),
    ('0   4 * * *', 'django.core.management.call_command', ['clearsessions']),
]
finally, run this command to add all defined jobs from CRONJOBS to crontab (of the user which you are running this command with):

python manage.py crontab add
show current active jobs of this project:

python manage.py crontab show
removing all defined jobs is straightforward:

python manage.py crontab remove

此方法的GitHub,所以说还是多上Github

当然此文不是说让大家有问题就去GitHub或者其他论坛求助,遇到问题的时候首先自己得先想一想解决方法,实在不行再去求助,要不然脑子慢慢就不好使了

猜你喜欢

转载自blog.csdn.net/lockey23/article/details/80328373
今日推荐