首页 > 解决方案 > 如何在一个脚本中编写两个脚本计时器?

问题描述

假设我想同时执行两段代码,每段 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 秒执行一次do_somethingdo_something_else 。我怎样才能在 Python 中做到这一点?我用time.sleep()and while Trueloop来设置定时器间隔,但是如何同时实现两个定时器呢?我尝试在 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_FieldValue 是 dosomethingelse。

标签: python

解决方案


查看错误消息,您pywin32在未向我们显示的代码中使用。显然您正在使用 COM 对象。

根据这个答案

在 Windows 上,COM 对象以同样的方式受到保护。如果您在线程上创建 COM 对象,它不希望您尝试在不同的线程上访问它。

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


推荐阅读