python 一次性定时器,Python线程.计时器仅重复一次

def On_Instrumentation_StartAnimation():

"""

Syntax : On_Instrumentation_StartAnimation()

Purpose : Fired if the animation is started

Parameters : None

"""

print "----------------------------------------------------------------------------------------"

localtime = time.asctime(time.localtime(time.time()))

global start

start = time.clock()

print "The user entered Animation Mode at local time: ", localtime

print("This data has also been written to 'c:\dSPACE71\cdlog\cdlog.txt'")

threading.Timer(2, ExecuteDemo).start()

ExecuteDemo()

# Printing to the text file

file1 = open('c:\dSPACE71\cdlog\cdlog.txt', 'a')

file1.write("\n----------------------------------------------------------------------------------------")

file1.write("\nThe user entered Animation Mode at local time: ")

file1.write(localtime)

file1.close()

def ExecuteDemo()

.

.

.

Current_value = Current.Read()

localtime = time.asctime(time.localtime(time.time()))

print "The current reading at localtime:", localtime, "is", str(Current_value) + "."

# Printing to the text file

file1 = open('c:\dSPACE71\cdlog\cdlog.txt', 'a')

file1.write("\n----------------------------------------------------------------------------------------")

file1.write("\nThe current reading at localtime: ")

file1.write(localtime)

file1.write(" is: ")

file1.write(str(Current_value))

file1.close()

.

.

.

As you can hopefully see, I'm trying to repeat the ExecuteDemo() function every 2 seconds after the StartAnimation function is called. But my problem here is that my ExecuteDemo() only runs twice. How can I get it to keep repeating? Am I missing something?

解决方案

From the documentation:

class threading.Timer

A thread that executes a function after a specified interval has passed.

This means Threading.Timer will call a function after a specified period of time. And as you noticed, it gets called only once. The solution here will to have the timer set once again at the end of the ExecuteDemo(..) function.

def ExecuteDemo():

.

.

.

threading.Timer(2, ExecuteDemo).start()

In my opinion, the above method is a little inefficient. It is like every 2 seconds a new thread is being created, and once it executes the function, it dies before creating the next thread.

I would suggest something like this:

def ExecuteDemoCaller():

#while True: # or something..

while someCondition:

ExecuteDemo()

time.sleep(2)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值