我有一个在多个主机上执行的python代码。它应该向协调员发送消息。
def foo():
try:
#print(time.ctime())
MESSAGE = str(len(queueList))
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
sock.sendto(MESSAGE, ('10.0.0.1', 5005))
threading.Timer(15, foo).start()
except KeyboardInterrupt:
print('\nClosing')
raise
if __name__ == '__main__':
foo()
我希望所有这些主机都在某个时间(例如3:15)开始执行foo()。我是Python的新手,所以我没有找到任何答案。我该怎么办?
答案 0 :(得分:0)
以下将起作用
import datetime
from apscheduler.scheduler import Scheduler
# Start the scheduler
sched = Scheduler()
# Define the function that is to be executed
def my_job(text):
print text
# The job will be executed on November 6th, 2009
exec_date = datetime.date(2009, 11, 6)
job_time = datetime.datetime.combine(exec_date, datetime.time(23, 59, 8))
# Store the job in a variable in case we want to cancel it
job = sched.add_date_job(my_job, job_time, ['text'])
sched.start()
print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))
try:
# This is here to simulate application activity (which keeps the main thread alive).
while True:
time.sleep(2)
except (KeyboardInterrupt, SystemExit):
# Not strictly necessary if daemonic mode is enabled but should be done if possible
scheduler.shutdown()