我正在一个函数中创建一个apscheduler作业,请在before_first_request()中的flask应用中调用此函数。此作业每30秒触发一次功能(该功能在我的flask应用程序的另一个.py文件中)。根据一个特定的结果(来自另一个.py文件),我必须终止此apscheduler作业。
In app.py:
@myapp.before_first_request
def before_first_request():
..
..
check_conn()
then in checking.py, I'm creating and starting a Background_scheduler job.
def check_conn():
with myapp.test_request_context():
global process_scheduler
process_scheduler = BackgroundScheduler()
process_scheduler.add_job(func=send_conn_check, trigger="interval", seconds=10, id='conn_job')
process_scheduler.start()
atexit.register(lambda: process_scheduler.shutdown())
this 'send_conn_check' is in sendxx.py:
def send_conn_check():
.... # sends message at regular time interval
....
When a message is received for first time in backgrnd.py, the below function will do some work and then call 'check_state' method to remove the apscheduler job,
def call_conn_accept(ch, method, properties, body):
try:
print('Connection message from abc %r' % body)
json_str = body.decode('utf-8')
...
if accept == "ACCEPT":
check_state() # this function is defined in checking.py
Again in checking.py,
def check_state():
global process_scheduler
process_scheduler.remove_job(job_id='conn_job') #### At this point I have remove the process_scheduler job.
....
....
node1_CONN#调度程序发送消息
node1_CONN
node1_CONN
错误:根:发生了一个异常:(“未定义名称'process_scheduler'”,)#当在check.py中的check_state()中的process_scheduler被调用以删除apscheduler作业时。
来自abc'{“ node1”:“ ACCEPT”}'的连接消息
node1_CONN#收到以上消息后,调度程序应删除作业,但不会删除。再次发送“ node1_CONN”
错误:root:发生了异常:(“未定义名称'process_scheduler'”))
来自abc'{“ node1”:“ ACCEPT”}'的连接消息 ... ...
答案 0 :(得分:0)
我通过将逻辑放置在python的多处理进程中并在此多进程守护进程内启动线程以每隔x秒调用'send'函数并在同一函数的另一个函数中满足条件时取消线程来解决了该问题多进程守护程序。
from multiprocessing import Process
class processClass:
def __init__(self):
print("Starting the multiprocess app...")
p = Process(target=self.run, args=())
p.daemon = True # Daemonize it
p.start() # Start the execution
def run(self):
#with myapp.test_request_context():
print('listening...')
send_conn_check() # Calling send function thread
listen_state() # Calling receive function.
def send_conn_check():
global t
t = threading.Timer(10, send_conn_check) #Thread
t.daemon = True
t.start()
...
...
def listen():
try:
...
...
if accept == 'ACCEPT':
t.cancel() # Cancel the thread when a condition is met
check_state()