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 Python uses timing to schedule tasks

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

Editor to share with you how to use Python to schedule tasks, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!

1. Simple cycle Simple loops

Using a simple loop to schedule tasks is effortless. Calling functions periodically using an infinitely running while loop can be used to schedule jobs, but this is not the best way, but it is very effective. You can use slleep () of the built-in time module to delay execution. However, this is not the way most jobs are scheduled, because it looks ugly and is less readable than other methods.

Import timedef task (): print ("Job Completed!") While 1: task () time.sleep (10)

Things get tricky when it comes to schedules such as 9:00 every morning or 7:45 every Wednesday night.

Import datetimedef task (): print ("Job Completed!") While 1: now = datetime.datetime.now () # schedule at every wednesday,7:45 pm if now.weekday = = 3 and now.strftime ("% HGV% m") = "19:45": task () # sleep for 6 days time.sleep (6 * 24 * 60 * 60)

This is the solution that I thought of at the first time, you're welcome! One problem with this approach is that the logic here is blocked, that is, once this code is found in the python project, it gets stuck in the while 1 loop, blocking the execution of other code.

2. Simple loop but using thread Simple loops but threaded

Threading is a concept in computer science. Mini Program with its own instructions is executed by the process and managed independently, which solves the blocking situation of our first approach. Let's see what happens.

Import timeimport threadingdef task (): print ("Job Completed!") def schedule (): while 1: task () time.sleep (10) # makes our logic non blockingthread = threading.Thread (target=schedule) thread.start ()

After a thread starts, its underlying logic cannot be modified by the main thread, so we may need to add resources through which programs can check specific scenarios and execute logic against them.

3. Timing scheduling library Schedule Library

Earlier, I said that scheduling using while loops looks ugly, and the scheduling library can solve this problem.

Import scheduleimport timedef task (): print ("Job Executing!") # for every n minutesschedule.every (10) .minutes.do (task) # every hourschedule.every (). Hour.do (task) # every daya at specific timeschedule.every (). Day.at ("10:30") .do (task) # schedule by name of dayschedule.every (). Monday.do (task) # name of day with timeschedule.every (). Wednesday.at ("13:15") .do (task) while True: Schedule.run_pending () time.sleep (1)

As you can see, in this way we can easily create multiple scheduling plans. I particularly like the way jobs are created and the method chain (Method Chaining). On the other hand, this fragment has a while loop, which means that the code is blocked, but I'm sure you already know what can help us solve this problem.

4 、 Python Crontab

The crontab utility in Liunx is an easy-to-use and widely accepted scheduling solution. The Python library python-crontab provides an API to use the CLI tool in Python. In crontab, a scheduled schedule is described in the unix-cron string format (*), which is a line of five values, indicating that when the job should be executed, python-crontab converts the plan to write the crontab in the file to the write programming method.

From crontab import CronTabcron = CronTab (user='root') job = cron.new (command='my_script.sh') job.hour.every (1) cron.write ()

Python-crontab does not automatically save the plan, and you need to execute the write () method to save the plan. There are more features, and I strongly recommend that you check their documentation.

5. RQ scheduler RQ Scheduler

Some tasks cannot be executed immediately, so we need to create a task queue and pop up a task based on a queuing system such as LIFO or FIFO. Python-rq allows us to do this, using Redis as a proxy to queue jobs. The entries for the new job are stored as hash maps with information, such as created_at, enqueued_at, origin, data, description.

Queuing tasks are performed by a program named worker. Workers also has an entry in the Redis cache that is responsible for dequeuing tasks and updating task status in Redis. Tasks can be queued when needed, but to schedule them, we need rq-scheduler.

From rq_scheduler import Schedulerqueue = Queue ('circle', connection=Redis ()) scheduler = Scheduler (queue=queue) scheduler.schedule (scheduled_time=datetime.utcnow (), # Time for first execution, in UTC timezone func=func, # Function to be queued args= [arg1, arg2], # Arguments passed into function when executed kwargs= {' foo': 'bar'}, # Keyword arguments passed into function when executed interval=60 # Time before the function is called again, in seconds repeat=None, # Repeat this number of times (None means repeat forever) meta= {'foo':' bar'} # Arbitrary pickleable data on the job itself)

The RQ worker (RQ worker) must be started separately in the terminal or through the python-rq worker. Once the task is triggered, you can see in the work terminal that separate function callbacks can be used in both success and failure scenarios.

The above is all the contents of the article "how Python uses scheduled tasks". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

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: 0

*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

Development

Wechat

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

12
Report