0

I have a Python script that executes every minute on my Raspberry Pi. What I want to do now is that this infinite loop that repeats itself every minute, starts at an specific date that I can control, let's say in a month or on July 17th, whatever date I set. I have seen how to get today's date, but not to run something on an specific day and time.

This is the code that I have:

import schedule
import time

def job():
    #HERE IS WHERE I WRITE THE TASK


schedule.every(1).minutes.do(job)


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

What do you guys suggest?

4

Use cron; it's designed for this. Trying to accomplish your objective in Python is like... I don't know, swatting flies with a sledgehammer? But that's strictly your choice of course.

cron is really quite easy to use, and the documentation is on your system:

man cron 
man crontab

Briefly, you'll edit your crontab as follows:

crontab -e

and you'll create a "schedule" for executing your Python program. Also, Debian (and therefore Raspbian) support non-standard schedules, including @reboot which runs a job/script/whatever when the machine reboots. Lots of online resources available for "hacking" cron:

2

You could try this if you want to incorporate the delay into your code:

import datetime
from time import sleep
import schedule

day_to_run = 10 # run this starting on the 10th
month_to_run = 5 # run this in may(the 5th month)

def job():
    #HERE IS WHERE I WRITE THE TASK

while 1:
    date = datetime.datetime.now()
    if date.day == day_to_run and date.month == month_to_run:
        break # this breaks out of the while loop if it's the right day.
    else:
        sleep(60) #wait 60 seconds

schedule.every(1).minutes.do(job) #continue with the rest of the program

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

Or you could use cron, as @Fabian says, which would schedule the script to run on a certain day:

en.wikipedia.org/wiki/Cron

https://kvz.io/blog/2007/07/29/schedule-tasks-on-linux-using-crontab/

running cron specific day of the month

Hope this helps!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.