python-3.x - 将对象作为函数的参数传递给作业调度程序
问题描述
我尝试使用 apscheduler 将对象作为参数传递给作业函数。这很好,但在我的情况下,我想更改它的一个值并在触发作业时使用更新的值。这是我的示例代码
import time
import sqlalchemy
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
class MyClass:
def __init__(self, *args, **kwargs):
self.state = kwargs.get('state', "")
jobstores = {
'default': SQLAlchemyJobStore(url='sqlite:///sched.db', tablename='apscheduler_jobs')
}
scheduler = BackgroundScheduler()
scheduler.configure(timezone='Europe/Paris')
scheduler.add_jobstore(jobstores['default'], 'default')
def myFunction(_internals):
print("- in job")
print(_internals.__dict__)
print(".")
if __name__ == "__main__":
scheduler.start()
myInstance = MyClass(state="off")
print(myInstance.__dict__)
j1 = scheduler.add_job(myFunction, trigger='cron', args=[myInstance], second='*/10', max_instances=10, jobstore='default', srv_id="blablabla-x6548710")
try:
# This is here to simulate application activity (which keeps the main thread alive).
while True:
time.sleep(2)
myInstance.__setattr__("state", "running")
print(myInstance.__dict__)
except (KeyboardInterrupt, SystemExit):
print('exit')
scheduler.shutdown()
这是我的期望:
{'state': 'running'}
{'state': 'running'}
{'state': 'running'}
{'state': 'running'}
{'state': 'running'}
in job
{'state': 'running'}
.
{'state': 'running'}
但相反,我有:
{'state': 'running'}
{'state': 'running'}
{'state': 'running'}
{'state': 'running'}
{'state': 'running'}
in job
{'state': 'off'}
.
{'state': 'running'}
有没有办法在 while 循环和触发这个时的作业中具有相同的值?
谢谢男孩女孩
解决方案
原来,工作中的 myInstance 是一个完全不同的对象。因此,它不受循环中所做的任何更改的影响。我使用了另一种策略:使用 memcached 在循环和计划作业之间进行通信。仍然对任何其他建议持开放态度。
推荐阅读
- assembly - 当我从堆栈中弹出时,该值被删除;为什么?
- python - 在一个包含 5 个 Excel 文件的文件夹中,每个文件有 3 个工作表,我想选择工作表 3 列 -a,c 并将其复制到 Excel 中,但具有不同的列
- r - 如何在注释中加粗部分文本(ggplot2)
- ajax - Ajax 将 Null 传递给控制器
- typo3 - Typo3 - 在 TypoScript 中为 DataQueryProcessor 使用 FlexForm 值
- android - 如何在 Firebase 数据库和 android studio 中以编程方式添加新节点和数据
- visual-studio-code - javascript调试终端使用powershell而不是git bash不断打开
- android - Flutter/Android:如何在 Flutter 中操作音频文件?
- python - 从csv中查找python列表中的索引并组合标签
- python - Numba - 在 jitclass 中使用 jitclass