通过Python3实现任务的定时循环执行


当前第2页 返回上一页

threading模块使用:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

import threading ,time

from time import sleep, ctime

class Timer(threading.Thread):

        """

        very simple but useless timer.

        """

        def __init__(self, seconds):

                self.runTime = seconds

                threading.Thread.__init__(self)

        def run(self):

                time.sleep(self.runTime)

                print ("Buzzzz!! Time's up!")

class CountDownTimer(Timer):

        """

        a timer that can counts down the seconds.

        """

        def run(self):

                counter = self.runTime

                for sec in range(self.runTime):

                        print (counter)

                        time.sleep(1.0)

                        counter -= 1

                print ("Done")

  

class CountDownExec(CountDownTimer):

        """

        a timer that execute an action at the end of the timer run.

        """

        def __init__(self, seconds, action, args=[]):

                self.args = args

                self.action = action

                CountDownTimer.__init__(self, seconds)

        def run(self):

                CountDownTimer.run(self)

                self.action(self.args)

  

def myAction(args=[]):

        print ("Performing my action with args:")

        print (args)

  

if __name__ == "__main__":

        t = CountDownExec(3, myAction, ["hello", "world"])

        t.start()

        print("2333")

Sched模块使用:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

'''

使用sched模块实现的timer,sched模块不是循环的,一次调度被执行后就Over了,如果想再执行,

可以使用while循环的方式不停的调用该方法

'''

import time, sched

#被调度触发的函数

def event_func(msg):

    print("Current Time:", time.strftime("%y-%m-%d %H:%M:%S"), 'msg:', msg)

def run_function():

    #初始化sched模块的scheduler类

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

    #设置一个调度,因为time.sleep()的时间是一秒,所以timer的间隔时间就是sleep的时间,加上enter的第一个参数

    s.enter(0, 2, event_func, ("Timer event.",))

    s.run()

def timer1():

    while True:

        #sched模块不是循环的,一次调度被执行后就Over了,如果想再执行,可以使用while循环的方式不停的调用该方法

        time.sleep(1)

        run_function()

if __name__ == "__main__":

    timer1()

以上就是通过Python3实现任务的定时循环执行的详细内容,更多文章请关注木庄网络博客!!

返回前面的内容

相关阅读 >>

Python自学用什么书

Python中正则表达式的应用讲解

如何实现redis队列优先级代码实例详解

Python中del函数的用法

Python缩进规则叫什么

Python中yaml配置文件模块的使用详解

Python中元类与枚举类的介绍(代码示例)

Python如何实现从 str 和 list的互相转化

Python spyder界面无法打开的解决方法

Python函数之compile()函数

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...