Jiechao Li
Jiechao Li

Reputation: 366

Python Cron job on Ubuntu

I have a python program that I want to run every 10 seconds, just like cron job. I cannot use sleep in a loop because the time interval would become uncertain. The way I am doing it now is like this:

interval = 10.0
next = time.time() 

while True: 
    now = time.time() 
    if now < next: 
        time.sleep(next - now) 
        t = Thread(target=control_lights,)
        t.start()# start a thread
    next += interval 

It generates a new thread that executes the contro_lights function. The problem is that as time goes, the number of python process grows and takes memory/CPU. Is there any good way to do this? Thanks a lot

Upvotes: 1

Views: 401

Answers (3)

ranni rabadi
ranni rabadi

Reputation: 324

You can run a cron job every 10 seconds, just set the second param to '0/10'. It will run on 0, 10, 20 etc

#run every 10 seconds from mon-fri, between 8-17
CronTrigger(day_of_week='mon-fri', hour='8-17', second='0/10')

Upvotes: 0

SlappyTheFish
SlappyTheFish

Reputation: 2384

Take a look at a program called The Fat Controller which is a scheduler similar to CRON but has many more options. The interval can be measured from the end of the previous run (like a for loop) or regularly every x seconds, which I think is what you want. Particularly useful in this case is that you can tell The Fat Controller what to do if one of the processes takes longer than x seconds:

  • run a new instance anyway (increase parallel processes up to a specified maximum)
  • wait for the previous one to finish
  • kill the previous one and start a new one

There should be plenty of information in the documentation on how to get it set up.

Upvotes: 1

versus.ua
versus.ua

Reputation: 9

may be try use supervisord or god for this script? It is very simple to use and to control a number of you'r processes on UNIX-like operating system

Upvotes: 1

Related Questions