0

Is there a better way to deal with a problem like this, avoiding some many useless comparisons?

import time

logClock = time.time()

while True:
    #Do something every 15 minutes
    if (time.time() - logClock) > 900:
        logClock = time.time()
        #Do something

Thank you!

5
  • sure but being uselessly executed several times. is there anything like a alarm clock or something? Commented Dec 22, 2014 at 11:27
  • You can use time.sleep() instead of if condition. Commented Dec 22, 2014 at 11:28
  • Tanveer - But that blocks possible remaining code to be executed right? Commented Dec 22, 2014 at 11:29
  • You need a separate thread that wakes up every 15 minutes to do something; in that thread you can let it sleep for the interval. As its not blocking the main thread you won't face this problem. Commented Dec 22, 2014 at 11:34
  • related: Python Equivalent of setInterval()?. Check out links I've provided there. Commented Dec 22, 2014 at 17:19

2 Answers 2

1

Hey while you can use an infinity loop with sleep, I would recommend to use Cron.

Since your goal is to run a script every period of time, with Cron you can schedule scripts like that.

If I'm not worng this is what you need in you Cron jobs file:

*/15 * * * * /usr/bin/python /path/to/script.py

When using Python you can do that with code-only via python-crontab lib.

Goodluck.

Sign up to request clarification or add additional context in comments.

1 Comment

The OP cannot use sleep as the OP wants the other code to continue
0

I decided to use a timer:

def wlanCheck():
    #Do something..

    #Timer controller...
    if util.getThreadKill() != 1:
        global tWLAN
        tWLAN = 0
        tWLAN = Timer(900, wlan.WLAN_check)
        tWLAN.start()

tWLAN = Timer(900, wlan.WLAN_check)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.