简体   繁体   中英

How to auto-run a script when a condition is true?

Let's say I have the following python program:

def Is_it_Midnight(args):
    print("It's midnight!")

and I want the .py script to execute itself when a certain condition is true, say "when the clock strikes midnight".

Is that possible?

You can use the threading library to have the routine restart itself periodically. In this specific case, every 86400 seconds (1 day).

modify your code to:

import threading
import time

def Is_it_Midnight(args):
    threading.Timer(86400, Is_it_Midnight).start()
    print("It's midnight!")

Then you just have to get the code to run at midnight the first time. Something like:

seconds = time.time()
since_midnight = seconds % 86400
time.sleep(86400-since_midnight)
Is_it_Midnight()

I'm not sure how you'd handle passing args into the routine.

There are a few options to run a script.

My favorite is to create myscript.py and within it define a function, let's say def alarm()... and then in your main script:

import myscript

And when the time comes, call:

myscript.alar()

There is another way, you can call execfile("myscript.py")

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