简体   繁体   中英

How to call a function periodically in a script scheduled with crontab?

I wrote a python script which makes calculation at every hour. I run this script with crontab scheduled for every hour. But there is one more thing to do; Additionally, I should make calculation once a day by using the results evaluated at every hour. In this context, I defined a thread function which checks the current time is equal to the specified time (15:00 PM, once a day ). If it is, thread function is called and calculation made. What I wanna ask here is; is this approach applicable ? I mean, running the first script at every hour using crontab, and calling the second function using thread function once a day. Is there any other way of doing this ?

You may use python library sched .

It efficient way to schelude your operations.

You could do a script which runs all the time and just sleeps for one hour.

import time

hours_ran = 0
while True:
    # your stuff here
    time.sleep(3600)
    hours_ran += 1
    if hours_ran == 24:
        # calculate stuff
        hours_ran = 0

This is not necessarily better tho... You can setup systemd to manage this process.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM