简体   繁体   中英

How to run a python function every day at specific time

I am trying to run a specific function every day at 18:00, I wrote the folwing code to do that but it did nothing

    today = datetime.today()
    nextDay = (today + timedelta(days=1)).replace(hour=18, minute=0, second=0)
    delta_time = nextDay - today
    secs = delta_time.seconds + 1
    timer = Timer(secs, self.send_officer_report(".send officer report --ad " + today.strftime("%Y/%m/%d"), today.strftime("%Y/%m/%d")))
    timer.start()

I do not want to use cron , I want my script to be OS independent

cron and related applications are the basic way to do this. With your approach, you have to keep the Python interpreter running 24/7, and if it crashes, all your times are off.

I found the answer here https://stackoverflow.com/a/16786600/9308420

import schedule
import time

def job():
    print("I'm working...")

schedule.every(10).minutes.do(job)
schedule.every().hour.do(job)
schedule.every().day.at("10:30").do(job)

while 1:
    schedule.run_pending()
    time.sleep(1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM