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!

  • sure but being uselessly executed several times. is there anything like a alarm clock or something? –  Dec 22 '14 at 11:27
  • You can use `time.sleep()` instead of `if` condition. – Tanveer Alam Dec 22 '14 at 11:28
  • Tanveer - But that blocks possible remaining code to be executed right? –  Dec 22 '14 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. – Burhan Khalid Dec 22 '14 at 11:34
  • related: [Python Equivalent of `setInterval()`?](http://stackoverflow.com/q/2697039/4279). Check out links I've provided there. – jfs Dec 22 '14 at 17:19

2 Answers2

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.

Or Duan
  • 13,142
  • 6
  • 60
  • 65
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)