Can i set a threading timer with clock time to sync with cron job in python

2024/11/19 11:43:01

I have a cron job that runs at 12, 12:30,1, 1:30. So every half hour intervals on the clock. I want to run a thread in my python code whenever the cron job runs.

I have seen examples where to run a timer every x seconds/mintues.But if I start my python code at 1:15pm for example if I set a timer for every 30 mins, the next time it will run is at 1:45pm. I want to thread to run at 1:30pm though. Is that possible?

Answer

Almost everything is possible, the real question is why do you want to do this? Keep in mind that cron scheduler won't necessarily execute jobs at precise times and furthermore, checking the time in Python won't necessarily correspond to cron's time, so if you need to execute something in your Python code after a cron job is executed, you cannot rely on measuring timings in Python - you actually need to 'communicate' from your cron job to your Python script (the easiest would be using datagram sockets)

But, if you want to simulate cron scheduler in Python, one way to do it is to use the datetime module to get the current time and then calculate the amount of time.sleep() you need before your command fires again, e.g.:

def schedule_hourly_task(task, minute=0):# get hourly offset in seconds in range 1-3600period = ((60 + minute) % 60) * 60 or 3600while True:# get current timecurrent = datetime.datetime.now()# count number of seconds in the current houroffset = (current - current.replace(minute=0, second=0, microsecond=0)).total_seconds()# calculate number of seconds til next periodsleep = period - offset % periodif offset + sleep > 3600:  # ensure sleep times apply to full hours onlysleep += 3600 % period# sleep until the next periodtime.sleep(sleep)# run the task, break the loop and exit the scheduler if `False` is returnedif not task():return

Then you can use use it to run whatever task you want at any full_hour + minute offset. For example:

counter = 0
def your_task():global countercounter += 1if counter > 2:return Falsereturn Trueschedule_hourly_task(your_task, 15)

And it will execute your_task() function every 15 minutes until your_task() returns False - in this case at hh:15, hh:30 and hh:45 before exiting. In your case, calling schedule_hourly_task(your_task, 30) will call the your_task() function every full 30 minutes for as long as your_task() returns True.

https://en.xdnf.cn/q/118545.html

Related Q&A

How do I make a simple countdown time in tkinter?

I am making a simple countdown timer in minutes. I cant seem to display the countdown in text label. Can someone help me?import tkinter as tk import timedef countdown(t):while t:mins, secs = divmod(t,…

Embed one pdf into another pdf using PyMuPDF

In need of help from learned people on this forum. I just want to embed one pdf file to another pdf file. So that when I go to the attachment section of the second file I can get to see and open the fi…

How to fix - TypeError: write() argument must be str, not None

Here is my code - sentence = input("Enter a sentence without punctuation") sentence = sentence.lower() words = sentence.split() pos = [words.index(s)+1 for s in words] hi = print("This s…

Is there a way to get source of a python file while executing within the python file?

Assuming you have a python file like so#python #comment x = raw_input() exec(x)How could you get the source of the entire file, including the comments with exec?

How can I stop find_next_sibling() once I reach a certain tag?

I am scraping athletic.net, a website that stores track and field times. So far I have printed event titles and times, but my output contains all times from that season rather than only times for that …

How can I make a map editor?

I am making a map editor. For 3 tiles I have to make 3 classes: class cloud:def __init__(self,x,y,height,width,color):self.x = xself.y = yself.height = heightself.width = widthself.color = colorself.im…

Counting total number of unique characters for Python string

For my question above, Im terribly stuck. So far, the code I have come up with is:def count_bases():get_user_input()amountA=get_user_input.count(A)if amountA == 0:print("wrong")else:print (&q…

adding a newly created and uploaded package to pycharm

I created a package (thompcoUtils) on test.pypi.org and pypi.org https://pypi.org/project/thompcoUtils/ and https://test.pypi.org/project/thompcoUtils/ show the package is installed in both the test an…

Using builtin name as local variable but also as builtin [duplicate]

This question already has answers here:UnboundLocalError trying to use a variable (supposed to be global) that is (re)assigned (even after first use)(14 answers)Closed 1 year ago.I have the following f…

How to print the results of a SQLite query in python?

Im trying to print the results of this SQLite query to check whether it has stored the data within the database. At the moment it just prints None. Is there a way to open the database in a program like…