Implement scheduled task management using Python’s built-in sched module

Scheduled task management is a common requirement in programming

We often encounter application scenarios that require scheduled tasks. Such as backing up the database regularly, sending text messages regularly, publishing subscription information and other scenarios. Use Windows' task manager and Linux's crontab to manage scheduled tasks, which need to be added manually. The configuration workload is heavy and cannot meet the scenario of automatically adding scheduled tasks. Of course, scheduled task management can be achieved through the third-party library celery, but celery is more complicated to use and requires additional development work.
The good news is that the python standard library provides a built-in module schedto manage scheduled tasks, does not rely on any third-party libraries, and is easy to use. Another benefit of the sched module is that it is platform independent and can run on any operating system.

Programming steps for using sched to manage scheduled tasks

1) Create a new sched object

import sched
import time
scheduler ``=` `sched.scheduler(time.time, time.sleep)

2) Define task function

The task function contains the work that is scheduled to be performed. If different work needs to be performed at two different times, the task should be split into two task functions.

3) Set task running time based on delay seconds

Use the sched.enter() method to schedule tasks, and the execution time is expressed as the number of seconds delayed from the current time.

grammar:scheduler.enter(delay, priority, action, argument=(), kwargs={})

Parameter Description:

  • delay: delay time, unit is seconds
  • priority: priority
  • action: task function
  • argument: task function parameter list (tuple format)
  • Variable parameter list of kwargs task function

4) Call the sched.run() method to start scheduled task monitoring

Start the schedule task queue, and after each task time is up, start the task function. The sched object exits only after all tasks in the queue have been executed.

Add tasks by absolute time:

The enter() method adds a task based on the number of seconds delayed from the current time. But we often encounter scenarios that require tasks to be performed at a certain point in time.

Usage; sched.enterabs()

Syntax: scheduler.enterabs(time, priority, action, argument=(), kwargs={})

Parameters:

  • time: The time when the task is executed, which can be in datetime format or stimulustamp time in float format.
  • priority: Priority value, the smaller the number, the higher the priority.
  • action: task function
  • argument: parameter tuple,

Complete example

import sched, time 
from datetime import datetime, timedelta

s = sched.scheduler(time.time, time.sleep)

def print_time(a: str='default'):
    # task function example
    print("From print_time", datetime.now(), a)

def calc_gap_second(dt: datetime):
    # get gap btw current time and input datetime, unit is second
    return dt.timestamp() - datetime.now().timestamp()

def print_some_times():
    print(datetime.now())
    t1= time.time()
    s.enter(10,1, print_time)   # 10秒后执行,优先级为1
    # 5秒后执行,优先级为2, 输入参数("test-2, ) 
    s.enter(5, 2, print_time, argument=('test_2',))  
    # 也是5秒后执行,用kwargs方式输入参数
    s.enter(5, 2, print_time, kwargs={
    
    'a': 'test_3'})
    # 预定在某个时间点执行,计算与当前时间的时差
    dt1 = datetime.strptime("2023-08-15 16:25:00:000001", "%Y-%m-%d %H:%M:%S:%f")
    s1: float = calc_gap_second(dt1)
    print("s1:",s1)
    # 根据计算好的时差来添加任务。
    s.enter(s1, 1, print_time, kwargs={
    
    'a': 'test_4'})
    # 用enterabs()方法,以时间点来添加任务
    s.enterabs(t1+6,1, print_time, kwargs={
    
    'a': 'test_5'})
    s.run()   # 启动监视任务循环
    print(time.time)

print_some_times()

output

2023-08-15 16:24:44.827923
s1: 15.162081003189087
From print_time 2023-08-15 16:24:49.830699 test_2
From print_time 2023-08-15 16:24:49.830699 test_3
From print_time 2023-08-15 16:24:50.833527 test_5
From print_time 2023-08-15 16:24:54.829681 default
From print_time 2023-08-15 16:25:00.005648 test_4

Task queue management

View all tasks
sched.queue task queue examples

Cancel task

sched.cancel(event) cancels a single task.
event is the task object returned after enter() and enterabs() add tasks.

e1 = scheduler.enter(1, 1, print_event,('1 st', ))

Determine whether the task queue is empty

shed.empty() checks whether the queue is empty, and returns True if it is empty.

Example

import sched
import time

scheduler = sched.scheduler(time.time, time.sleep)
  
def print_event(name):
    print('EVENT:', time.time(), name)

print ('START:', time.time())
e1 = scheduler.enter(1, 1, print_event,('1 st', ))
e2 = scheduler.enter(2, 1, print_event,(' 2nd', ))
scheduler.cancel(e1)
print("schedule queue length:", len(s.queue))
scheduler.run()

output:

START: 1580390119.54074
schedule queue length: 1
EVENT: 1580390121.5439944  2nd

Advanced scheduled task management libraries, such as APScheduler , can implement more complex scheduled task management.

Guess you like

Origin blog.csdn.net/captain5339/article/details/132302634