5

I want to run a program that runs a function every 4 hours. What is the least consuming way to do so?

Asaf
  • 8,106
  • 19
  • 66
  • 116
  • Least consuming? Please clarify – rossipedia May 17 '10 at 19:26
  • 2
    What operating system are you using? If it is unix, then the answer is most likely cron... – unutbu May 17 '10 at 19:26
  • 2
    What platform? On Unix/Linux, the at/cron mechanism are the right way to do it. On Windows you have to create a service, and register its UUID and arrange for it to be started on boot, and send your firstborn to Redmond, or sumptin like that... – msw May 17 '10 at 19:28
  • 4
    Why aren't you using `cron` on linux or `at` on Windows? – S.Lott May 17 '10 at 19:34
  • well, I am planning to give this software for friends on multiple OS's, so it would have to be none-OS specific.. I see that nobody is stressing that Bryan's answer is fundamentally wrong CPU wise so I'll use his. – Asaf May 17 '10 at 20:07
  • you can also take a look at [sched](http://docs.python.org/library/sched.html) – Amr Jun 05 '12 at 17:06

3 Answers3

6

Simlest way I can think of (in python since the post is tagged with python):

import time

while True:
  do_task()
  time.sleep(4 * 60 * 60) # 4 hours * 60 minutes * 60 seconds
rossipedia
  • 56,800
  • 10
  • 90
  • 93
  • ok that works very well, however I'm troubled CPU power used, or is it pretty much efficiency proof? – Asaf May 17 '10 at 19:35
  • 1
    "efficiency proof?" What does that mean? Do you think it uses the CPU while sleeping? – S.Lott May 17 '10 at 20:42
  • 3
    It's pretty much safe to say that it just puts the process to sleep. Virtually zero CPU use until it wakes up. – rossipedia May 17 '10 at 21:02
  • time.sleep() is not accurate. You should use time.sleep() in repeated intervals via a loop to perform a check if the elapsed time meets the expected time. You can use time.time() to get the current time, add the difference to it and then use time.sleep() in a loop to see if time.time() >= expected time. This isn't a suggestion for scheduling but just a simple solution for simple time based delays. For 4 hours, `expected_time = time.time() + (4 * 60 * 60)`. – jetole Aug 04 '19 at 02:12
5

You can use sched module

Here are the docs

https://docs.python.org/3.4/library/sched.html

3

Use the build in timer thread:

from threading import Timer

def function_to_be_scheduled():
   """Your CODE HERE"""

interval = 4 * 60 * 60   #interval (4hours)

Timer(interval, function_to_be_scheduled).start() 
liuroot
  • 111
  • 2
  • 2
  • 5