如何在一个脚本中编写两个脚本定时器?

2024-10-03 06:23:53 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我想同时执行两段代码,每3秒和0.1秒执行一段。我该怎么做?你知道吗

我将使用VBScript作为示例:

Sub ScriptStart
    View.SetTimerInterval1(3000)
    View.SetTimerInterval2(100)
    View.EnableTimer1(True)
    View.EnableTimer2(True)
End Sub

Sub ScriptStop
    View.EnableTimer1(False)
    View.EnableTimer2(False)

Sub OnScriptTimer1
    dosomething
End Sub

Sub OnScriptTimer2
    dosomethingelse
End Sub

代码应该让两个脚本计时器每3秒0.1秒执行一次。我怎样才能用Python来做呢?我使用time.sleep()while True循环来设置计时器间隔,但是如何同时实现两个计时器呢?我尝试在Python中使用线程:

def OnProjectRun:
    t1 = threading.Thread(target=OnScriptTimer1)  
    t2 = threading.Thread(target=OnScriptTimer2) 
    t1.start()
    t2.start()

def OnScriptTimer1:
    dosomething()

def OnScriptTimer2:
    dosomethingelse()

def dosomething:
    #acutual code

def dosomethingelse:
    #actual code

然后我得到一个错误:

Traceback (most recent call last):
  File "C:\Python25\Lib\threading.py", line 486, in __bootstrap_inner
    self.run()
  File "C:\Python25\Lib\threading.py", line 446, in run
    self.__target(*self.__args, **self.__kwargs)
  File "PyEditView1", line 314, in OnScriptTimer2
  File "PyEditView1", line 230, in Get_FieldValue
  File "C:\Python25\lib\site-packages\win32com\client\__init__.py", line 463, in __getattr__
    return self._ApplyTypes_(*args)
  File "C:\Python25\lib\site-packages\win32com\client\__init__.py", line 456, in _ApplyTypes_
    self._oleobj_.InvokeTypes(dispid, 0, wFlags, retType, argTypes, *args),
com_error: (-2147417842, 'The application called an interface that was marshalled for a different thread.', None, None)

在本例中,Get\u FieldValue是dosomethingelse。你知道吗


Tags: inpyselfviewtruedeflinefile
2条回答

查看Python的调度程序模块;sched。我想你可以调整它来满足你的需求需要。这里是一个让你开始的例子

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

def on_script_timer1():
    print("Timer1")
    s.enter(3, 1, on_script_timer1)
    s.run()

def main():
    print(time.time())
    s.enter(3, 1, on_script_timer1)
    s.run()

if __name__ == '__main__':
    main()

1566225979.83796
定时器1
定时器1
定时器1
定时器1


您还可以使用计时器;tutorial

import threading 
def mytimer(): 
   print("Python Program\n") 
my_timer = threading.Timer(3.0, mytimer) 
my_timer.start() 
print("Bye\n") 

查看错误消息,您在没有显示的代码中使用了pywin32。显然你在使用COM对象。你知道吗

根据this answer

On Windows, COM objects are protected the same sort of way. If you create an COM object on a thread it doesn't like you trying to access it on a different thread.

所以,您可能在一个线程中创建了一些COM对象,然后尝试在另一个线程中使用它。Windows不喜欢这样,因此出现了错误。你知道吗

相关问题 更多 >