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 秒执行一次do_something和do_something_else 。我怎样才能在 Python 中做到这一点?我用time.sleep()
and while True
loop来设置定时器间隔,但是如何同时实现两个定时器呢?我尝试在 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。
解决方案
查看错误消息,您pywin32
在未向我们显示的代码中使用。显然您正在使用 COM 对象。
根据这个答案:
在 Windows 上,COM 对象以同样的方式受到保护。如果您在线程上创建 COM 对象,它不希望您尝试在不同的线程上访问它。
因此,您可能在一个线程中创建了一些 COM 对象,然后尝试在另一个线程中使用它。Windows 不喜欢这样,因此出现错误。
推荐阅读
- excel - 将多个 xlsl 文件转换为 xls (97-2003 Worksheet) 扩展名而不更改名称
- python - 尝试学习python并尝试定义函数时碰壁
- java - Android广播接收器单元测试IntentAction为空
- ms-access - 创建从 Ms Access 到 Sql-Server 的 Make 表
- java - 是否可以在单例中访问其他类的get方法
- shell - 如何将语义版本的 shell 变量转换为移位整数?
- symfony - Symfony / Twig:过滤器过滤集合
- amazon-web-services - 如何将架构批量添加到 Redshift 中的数据共享?
- facebook - Facebook 目录的微数据标签中的多个图像
- python - Discord py Emoji URL 问题