使用Django commands做定时(crontab)任务

需求: 我想调用django里models.py或者views.py的函数对数据库做些增删改查的操作,可以加入crontab做管理,找了半天才发现可以用django commands来搞,就简单记录下来怎么用。

这个app的内容如下:

tree weblog/
weblog/
├── __init__.py
├── __init__.pyc
├── admin.py
├── admin.pyc
├── apps.py
├── management
│   ├── __init__.py
│   ├── __init__.pyc
│   └── commands
│       ├── __init__.py
│       ├── __init__.pyc
│       ├── delete_author.py
│       └── delete_author.pyc
├── migrations
│   ├── 0001_initial.py
│   ├── 0001_initial.pyc
│   ├── __init__.py
│   └── __init__.pyc
├── models.py
├── models.pyc
├── tests.py
└── views.py

3 directories, 19 files

简单写一个函数,功能是删除weblog_author表的一条记录:

cat weblog/management/commands/delete_author.py

from django.core.management.base import BaseCommand, CommandError
from weblog.models import Author

class Command(BaseCommand):
    help = 'delete author'

    def add_arguments(self, parser):
        parser.add_argument('author_id', nargs='+', type=int)

    def handle(self, *args, **options):
        for author_id in options['author_id']:
            try:
                author = Author.objects.get(pk=author_id)
            except Author.DoesNotExist:
                raise CommandError('Author "%s" does not exist' % author_id)

            author.delete()

            self.stdout.write(self.style.SUCCESS('Successfully delete author "%s"' % author_id))

执行

python manage.py delete_author  2
Successfully delete author “2"

加入到crontab里:

*/15 * * * * python /var/www/poll_mysite/manage.py delete_author  2 >/dev/null 2>&1

参考资料:

Run Django commands using cron:https://coderwall.com/p/k5p6ag/run-django-commands-using-cron

扩展Django:实现自己的manage命令:http://www.cnblogs.com/holbrook/archive/2012/03/09/2387679.html

Writing custom django-admin commands:https://docs.djangoproject.com/en/1.10/howto/custom-management-commands/