The Sched module allows you to implement functions by customizing the time, custom functions, and custom precedence. Example One
1 Import Time2 Importsched3 4Schedule =Sched.scheduler (time.time,time.sleep)5 6 deffunc (string1):7 Print "Now excuted func is%s"%string18 9 Print "Start"TenSchedule.enter (2,0,func, (1,)) OneSchedule.enter (2,0,func, (2,)) ASchedule.enter (3,0,func, (3,)) -Schedule.enter (4,0,func, (4,)) - Schedule.run () the - Print "End"
Schedule is an object, what name can be Schedule.enter (delay,priority,action,arguments) The first argument is an integer or a floating-point number, Represents the number of seconds after which the action task is executed the second parameter is priority, 0 represents the highest priority, 1 times, and 2 times second, when two tasks are scheduled to execute at the same time, the priority determines who executes first. The third parameter is the task you are going to perform, you can simply understand the function of the functions you want to perform the function name of the fourth parameter is that you want to pass in this timing function name function parameters, preferably wrapped in parentheses, if only one parameter is passed in parentheses, the parameter must be appended with a comma, if you do not hit a comma, An error will occur. For example Schedule.enter (delay, priority, action, (argument1,)) run () has been blocked until all tasks have been executed at the end. Each task runs in the same thread, so if one task executes longer than the other, then the other tasks postpone the execution of the task so that no tasks are lost, but the call times for those tasks are deferred than the set.multithreading to perform timed tasksExample Two
1 Import Time2 Importsched3 fromThreadingImportTimer4 defprint_name (str):5 Print "i ' m%s"%Str6 Print "Start"7Timer (5,print_name, ("Superman",)). Start ()8Timer (10,print_name, ("Spiderman",)). Start ()9 Print "End"Through multi-threading, the implementation of timed tasks in multi-threading, if only through schedule, because of the problem of thread security will be blocked, one task execution, if there is no end and another task will wait. Through threading. The timer avoids this problem by directly executing print start and print end, while the timed task executes separately. Print end does not block.
Python Timer task-sched module