Как выполнить кусок кода в определенное время - PullRequest
0 голосов
/ 01 февраля 2019

У меня есть код 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()

Я хочу, чтобы все эти хосты начали выполнять foo () в определенное время, например в 3:15.Я новичок в Python, поэтому я не нашел ничего в качестве своего ответа.Как я могу это сделать?

1 Ответ

0 голосов
/ 01 февраля 2019

Следующее будет работать

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()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...