[英]How to test celery periodic_task in Django?
我有一個簡單的周期性任務:
from celery.decorators import periodic_task
from celery.task.schedules import crontab
from .models import Subscription
@periodic_task(run_every=crontab(minute=0, hour=0))
def deactivate_subscriptions():
for subscription in Subscription.objects.filter(is_expired=True):
print(subscription)
subscription.is_active = False
subscription.can_activate = False
subscription.save()
我想用測試來覆蓋它。
我找到了關於如何測試簡單任務的信息,比如@shared_task,但我找不到測試@periodic_task
的例子
當使用裝飾器定義周期性任務時,您可以通過以下方式訪問 crontab 配置:
任務.py
@periodic_task(
run_every=(crontab(minute="*/1")),
)
def my_task():
pass
一些您需要訪問它的文件
from .tasks import my_task
crontab = my_task.run_every
hours_when_it_will_run = crontab.hour
minutes_when_it_will_run = crontab.minute
day_of_the_week_when_it_will_run = crontab.day_of_week
day_of_the_month_when_it_will_run = crontab.day_of_month
month_of_year_when_it_will_run = crontab.month_of_year
通過這種方式,您可以訪問何時執行任務並檢查您的測試是否存在預期時間。
使用函數apply()
。 apply()
文檔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.