Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Celery to set scheduled tasks in Django

2025-04-07 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

It is believed that many inexperienced people have no idea about how to use Celery to set up scheduled tasks in Django. Therefore, this paper summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.

1. Celery joins scheduled tasks

In addition to asynchronously executing tasks, Celery can also execute tasks on a regular basis. Write a test method based on the example code:

# coding:utf-8from celery.task.schedules import crontab from celery.decorators import periodic_task @ periodic_task (run_every=crontab ()) def some_task (): print ('periodic task testing') Time.sleep (5) print ('success') return True

The code executes the some_task method every minute.

In the last article, you started celery using worker. However, worker cannot start scheduled tasks. The startup method is as follows:

1) make sure the middleman is open first. I use redis as the middleman. You can refer to the Redis installation process in CentOS and Windows.

2) go to the root directory of the django project and execute the following code to start the worker of celery:

There are two tasks, one of which myapp.tasks.sendmail is the asynchronous processing task added in the previous article. Myapp.tasks.some_task is the scheduled task this time.

3) also open a command line interface in the root directory of the django project and execute the following code:

2. Celery timing task time setting

If you think one minute is too long to wait. Can be set to perform scheduled tasks every 10 seconds. Modify the above periodic_task as follows:

@ periodic_task (run_every=10)

To modify the code, you need to restart worker and beat of Celery.

This run_every parameter sets the time interval or execution time for scheduled tasks. There are three ways to set this parameter.

1) set number of seconds directly

For example, the 10-second interval, run_every=10, performs a task every 10 seconds. One minute is 60 seconds; one hour is 3600 seconds.

2) set the time interval through datetime

Sometimes it is not convenient to set the number of seconds directly, and the specific number of seconds needs to be calculated.

For example, 1 hour, 15 minutes, 40 seconds = 1 "60" 60 + 15 "60 + 40. The readability of this situation is not high.

You can use the datetime setting as follows:

From celery.decorators import periodic_taskimport datetime @ periodic_task (run_every=datetime.timedelta (hours=1, minutes=15, seconds=40)) def some_task (): print ('periodic task testing')

The readability of the code is significantly improved and it is easy to set up.

However, this kind of time setting can not satisfy the time setting of the fixed point. Suppose I want to perform a task at 12:15 every day. Neither datetime nor directly setting the number of seconds can be achieved. The third way has to be used at this time.

3) crontab expression of celery

Crontab is a more sophisticated and slightly more complex approach (compared to the first two). Can achieve our various requirements for setting time.

For example, the code given earlier:

# coding:utf-8from celery.task.schedules import crontab from celery.decorators import periodic_task @ periodic_task (run_every=crontab ()) def some_task (): print ('periodic task testing')

It means that it is executed every 0 seconds (not to mention this 0 seconds later, everyone knows it, save your breath).

Where crontab () is instantiated without setting any parameters and uses the default value. Crontab has a total of 7 parameters, and five commonly used parameters are:

Minute: minutes, range 0-59

Hour: hours, range 0-23

Day_of_week: what day of the week, range 0-6. Start with Sunday, that is, 0 is Sunday. The day of the week can also be expressed by English abbreviations, such as "sun" for Sunday.

Day_of_month: date of each month, range 1-31

Month_of_year: month, range 1-12.

A, default parameters

These parameters can set expressions to express slightly more complex settings. The default value is the "*" asterisk, which represents any time. That is, crontab () is equivalent to:

Crontab (minute='*', hour='*', day_of_week='*', day_of_month='*', month_of_year='*')

It means to perform tasks every day, every hour, and every minute. This statement is too anti-human language habits, to put it simply, to perform a task every minute.

B, a specific value

The range of values for these parameters is mentioned above. We can set a value directly. For example:

Crontab (minute=15)

That is, to carry out the task every 15 minutes of the hour. Directly specify a certain time. And so on, the settings for executing tasks at 00:00 every day are as follows:

Crontab (minute=0, hour=0)

Of course, you can also set multiple values. For example, perform a task at 0 and 30:

Crontab (minute='0,30')

Strings are used here, and values are separated by commas. The comma here represents the or logical relationship of multiple expressions.

C, set the range

The setting range is also to set multiple values, such as specifying that tasks are executed every minute of each hour from 9 to 12:00.

Crontab (minute='*', hour='9-12')

Here the * sign is the default value, which can be omitted as follows:

Crontab (hour='9-12')

It is mentioned above that a comma is an or logical relationship. Expand and assign tasks every minute between 9 a.m. to 12:00 and 20:00:

Crontab (hour='9-12J 20')

The expression of crontab is getting more and more complex. Celery also provides a class to get the parsing result of the expression, as follows:

From celery.task.schedules import crontab_parserr = crontab_parser (23,0). Parse ('9-12 print 20') print (r)

Where crontab_parse is a parsing class. The first parameter is the maximum value of the range; the second parameter is the minimum value of the range. By entering the expression through parse, you can get the parsing result of the expression:

Set ([9,10,11,12,20])

We can use this method to verify the parsing results in many places below.

D. Set the interval step

If I want to set up tasks to be performed every minute every day in January, 3, 5, 7, September, and November, I can set up as follows:

Crontab (day_of_month='1,3,5,7,9,11')

According to the observation data, it can be found that it is the step size of interval 2. The number that needs to be set is relatively small, and it is troublesome to have more numbers. For example, I want to perform a task every 2 minutes. I find it troublesome to write 30 numbers. Crontab expressions also provide interval handling, such as:

Crontab (minute='*/2') crontab (minute='0-59max 2') # the effect is the same as above

This sign does not mean to divide by. Equivalent to the third parameter of range, for example:

Range (0,599,1,2)

That's all for crontab expressions, to give you a few more examples:

# perform a task every minute every 2 hours crontab (hour='*/2') # perform a task every 3 hours at the zero minute # that is, [0pr 3, hour='*/3' 6, 12je 15pm 18pm 21] crontab (minute=0, hour='*/3') # perform a task every 3 hours or at 0pm from 8: 00 to 12:00 # that is, [0p3pt 6pct # 12pct 1215pc18 21] + [8pcmlm12] 0pm crontab (minute=0) Hour='*/3,8-12') # in the first month of each quarter One task per minute per day in the month range is from 1 to 12, and every 3 months is crontab (month_of_year='*/3') # one task at 00:00 on an even number of days per month crontab (minute=0, hour=0, day_of_month='2-31 day_of_month='11', month_of_year='5' 2') # one task crontab (0,0, day_of_month='11', month_of_year='5') at 00:00 on May 11 every year

These expression settings can be validated with crontab_parser.

After reading the above, have you mastered how to use Celery to set up scheduled tasks in Django? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 247

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report