2

I need execute since an specific time a function every certain interval of time.

For example if the begining time is 00:00:00 and the the interval is 5 seconds then I need that the times of execution of this function are:

00:00:00
00:00:05
00:00:10
00:00:15
...
23:59:55

As you can see my point is the clock of the system

Exist many question with relationship this question in stackoverflow like How to execute a function asynchronously every 60 seconds in Python? and What is the best way to repeatedly execute a function every x seconds in Python?.Futhermore I see other solution with schedule 0.3.2.

My problem is that for example with this code:

import schedule
import time

def job():
    print("I'm working...")
    print 'execute f time: ', time.ctime(time.time())
    print 'execute f time: ', time.time()
schedule.every().minutes.do(job)

while 1:
    schedule.run_pending()
    time.sleep(1)

In this case when I run my code the output of my code is:

I'm working...
execute f time:  Wed Jul 13 04:32:00 2016
execute f time:  1468398720.88
I'm working...
execute f time:  Wed Jul 13 04:33:00 2016
execute f time:  1468398780.94
I'm working...
execute f time:  Wed Jul 13 04:34:01 2016
execute f time:  1468398841.0

As you can see this code is executed every minute, but the interval change from 1 minute to 1 minute an 1 second and this error is important for me, probably causes of the time of the function print. I need that continue executing every minutes in this case without seconds caused by the cumulative sum of the times of the function print

My solution with timer have the same error:

import threading
import time

def f():
    # call f() again in 10 seconds
    threading.Timer(10, f).start()
    # do something here ...
    print 'execute f time: ', time.time()
    time.sleep(5)

# start calling f now and every 10 sec thereafter
print 'init time: ', time.time()
f()

A fragment of the output shown that the comulative error in some moment causes an interval greater than 5 ( [0, 5, 10,16,21,26,....]) and this is wrong for me, because is important for me the time of execution of the function:

init time:  1468407868.6
execute f time:  1468407868.6
execute f time:  1468407878.6
execute f time:  1468407888.6
execute f time:  1468407898.6
execute f time:  1468407908.61  # change the interval
execute f time:  1468407918.61
execute f time:  1468407928.61

With the module sched I have the same problem

Please Any advise thanks in advance.

Update

Ok I test crontab and don't satisfy me. First I test this going to the file of configuration crontab of my user in Ubuntu, but later I found an library to write instruction to he crontab file configuration, so I use library Crontab

#!/usr/bin/python
# -*- coding: utf-8 -*-

from crontab import CronTab
task = CronTab(user='cyberguille')
command='/home/cyberguille/date.py'
cron_job=task.new(command)
cron_job.setall('*/1, *, *, *, *')
task.write()
print task.render()

As you can see every one minute execute code, but I see two problems, execute in less than one minute is no easy(see How to run scripts every 5 seconds using cron?) and I don't know why when I execute every one minute is every one minute with one second and we have too comulative sum error but the error fits better than the examples above

the code in date.py is this

#!/usr/bin/python
# -*- coding: utf-8 -*-

#import time
from datetime import datetime
tiempo = datetime.now()
#tiempo = time.strftime("%H:%M:%S")
archivo=open('/home/cyberguille/archivo_fecha.txt', 'a+')

archivo.write(str(tiempo) + '\n')

and a fragment of the output is

2016-07-19 00:11:01.307779
2016-07-19 00:12:01.365995
2016-07-19 00:13:01.421373
2016-07-19 00:14:01.477752
2016-07-19 00:15:01.532234
2016-07-19 00:16:01.588818
2016-07-19 00:17:01.649581
2016-07-19 00:18:01.705975
2016-07-19 00:19:01.759986
2016-07-19 00:20:01.816754
2016-07-19 00:21:01.873748
2016-07-19 00:22:01.927750
2016-07-19 00:23:01.980666
2016-07-19 00:24:02.036164
2016-07-19 00:25:01.090912
2016-07-19 00:26:01.148098

Really every one minute you can say that's not importan error, but why is not posible execute for example with the seconds in 00

2016-07-19 00:11:00.307779
2016-07-19 00:12:00.365995
2016-07-19 00:13:00.421373
2016-07-19 00:14:00.477752

Maybe the calling of the script is slow.

I found a solution with good results to me this is the script

    from multiprocessing import Process
    from datetime import datetime
    import time
    import sched

    def timer(interval):
            sc = sched.scheduler(time.time, time.sleep)
            sc.enter(1, 1, do_something, (sc,interval))
            sc.run()
     def do_something(sc,interval):
            dateTime = datetime.now()
            if(dateTime.second%interval==0):
                p = Process(target=SensorContainer.run,args=(dateTime,))
                p.start()
            sc.enter(1, 1, SensorContainer.do_something, (sc,interval,))


     def run(datetime):
            print datetime

with this solution the timer work every one minute in 0 seconds, as you can see my measure is when I call the function, that's not the same that in crontab, but in any case I test taking the time inside the run function an is 0 the seconds too.

Community
  • 1
  • 1
Cyberguille
  • 1,552
  • 3
  • 28
  • 58

1 Answers1

3

I believe that you are better off relying on the OS to do the scheduling than on Python. It will be simplier to have a simple script with a single function and then use crontab (if using Linux) or Windows Task Scheduler to schedule the execution.

One of the reasons to prefer the OS approach is robustness. For example, if you rely on Python for the scheduling, in case an unhandled exception occurs then your script will terminate until it will manually be executed again. Same goes for system reboots etc.

If you are are using the OS for scheduling, the script will keep executing in the predefined schedule even in cases of system reboots and unhandled exceptions.

DeepSpace
  • 78,697
  • 11
  • 109
  • 154
  • I use linux, maybe I can execute shell commands in Python to do this, because this code is part of a system developed in oython. Could you expand your answer about why is better to work with the OS than on python? – Cyberguille Jul 13 '16 at 10:02
  • Now I read about crontab, late I test your advice and if work for me as soon as I can I vote up and accept your answer – Cyberguille Jul 13 '16 at 11:09
  • I updated my question with one analysis about your suggestion, maybe exist other way to work with crontab and you can say me how, please give me your opinion about this. – Cyberguille Jul 24 '16 at 06:38