此使用線程可以做到安全的隊列
import logging
import Queue
from apscheduler import events
from apscheduler.scheduler import Scheduler
import time
#logging.basicConfig(level=logging.INFO,format='%(asctime)s : %(name)s : %(levelname)s : %(module)s.%(funcName)s(%(lineno)d) : %(thread)d %(threadName)s: %(message)s')
#enable logger to see exceptions caught by apscheduler
logging.basicConfig()
q = Queue.Queue()
sched = Scheduler()
@sched.interval_schedule(seconds=1)
def some_job():
msg = "Decorated job : %s" % time.time()
print msg
logging.info(msg)
q.put(msg)
q.put("message 2")
def job_listener(event):
#print str(event)
while not q.empty():
get_ = "msg from job '%s': '%s'" % (event.job, q.get())
print get_
logging.info(get_)
sched.add_listener(job_listener,
events.EVENT_JOB_EXECUTED |
events.EVENT_JOB_MISSED |
events.EVENT_JOB_ERROR)
config = {'apscheduler.jobstores.file.class': 'apscheduler.jobstores.shelve_store:ShelveJobStore',
'apscheduler.jobstores.file.path': '/temp/dbfile'}
sched.configure(config)
sched.start()
q.join()
while True:
pass
輸出:
Decorated job : 1363960621.39
msg from job 'some_job ...: 'Decorated job : 1363960621.39'
msg from job 'some_job ...': 'message 2'
Decorated job : 1363960622.4
msg from job 'some_job ...: 'Decorated job : 1363960622.4'
msg from job 'some_job ...: 'message 2'
Decorated job : 1363960623.39
有一個競爭條件嗎?我看不到隊列中的消息是如何與作業實際關聯的。作業1是否可能將消息放入隊列中,然後作業2在另一個線程中執行,並且作業2的事件首先被觸發,並且您看到它會打印來自作業1的消息「來自作業2的消息:」和旁邊的消息? – dmd 2015-09-23 16:59:43
是的,確認。不要使用上面的代碼!如果您有多個作業同時運行,則不會得到與正確消息關聯的正確作業ID。 – dmd 2015-09-23 17:20:09