Denkan
Denkan

Reputation: 65

Make a program restart regulary

I'm currently working on a project that I want to restart and rerun every 10 minutes. So I created this test file to see if I could get it working.

import sys
import os
import sched
import time

print("Hello")
s = sched.scheduler(time.time, time.sleep)

def restart_program(sc):
    python = sys.executable
    os.execl(python, python, * sys.argv)
    s.enter(5, 1, restart_program, (sc,))

s.enter(5, 1, restart_program, (s,))
s.run()

So I want this program to restart every 5 seconds. In this case it would print "Hello!". But when i run it, it just prints once and never restarts.

How would I make it restart regulary?

Upvotes: 1

Views: 426

Answers (2)

Pinna_be
Pinna_be

Reputation: 4617

Besides some possibilities for better choices, I think your code does not work because of the behaviour of os.execl:

These functions all execute a new program, replacing the current process; they do not return.

check out subprocess.Popen

   import sched
   import time
   import subprocess

   print("Hello")
   s = sched.scheduler(time.time, time.sleep)

   def restart_program(sc):
       subprocess.Popen(["echo", "external process is being called"])
       s.enter(5, 1, restart_program, (sc,))

   s.enter(5, 1, restart_program, (s,))
   s.run()

Upvotes: 0

Chankey Pathak
Chankey Pathak

Reputation: 21666

I don't get what exactly are you looking for but below are the 3 possible cases.

1: If the program is running (perhaps as a daemon?) and you want to keep calling a particular method after some interval then you can use apscheduler.

from apscheduler.schedulers.blocking import BlockingScheduler

def do_something_every_5_second():
    print "Do something"

scheduler = BlockingScheduler()
scheduler.add_job(do_something_every_5_second, 'interval', seconds=5)
scheduler.start()

2: You can use Cron which will execute your python script at defined time. Note that Cron can not be set for less than 1 minute. So for eg if you want to run your script through Cron every 5 seconds then you'll have to use below hack.

* * * * * /path/to/script
* * * * * sleep 5; /path/to/script
* * * * * sleep 10; /path/to/script
* * * * * sleep 15; /path/to/script
* * * * * sleep 20; /path/to/script
* * * * * sleep 25; /path/to/script
* * * * * sleep 30; /path/to/script
* * * * * sleep 35; /path/to/script
* * * * * sleep 40; /path/to/script
* * * * * sleep 45; /path/to/script
* * * * * sleep 50; /path/to/script
* * * * * sleep 55; /path/to/script

If you are on Windows then you can use Windows Task Scheduler. See Schedule Python Script - Windows 7

3: You can use loop with timeout (as suggested by Sneh)

Upvotes: 2

Related Questions