When writing the code, the following code will be activated on time, saying it is stopped until the hour.
However, to operate the code on time, it takes more than 59 minutes to run the code must run the code.
Is there a way to make it work at 12pm by adjusting the minutes and hours instead of seconds in that code?
enter code here`current_time = time.time()
time_to_sleep = (60 - (current_time % 60))
time.sleep(time_to_sleep)
Instead of sleep, you can pause until a defined time:
import pause
from datetime import datetime
pause.until(datetime(2022, 10, 25, 12))
or you can do it like this:
import datetime
import time
while datetime.datetime(2022,10,25,10,28,0) > datetime.datetime.now():
time.sleep(30)
pass
print("it's time to act")
but #Tanner version seems to be more preferable
Related
import datetime
import schedule
import time
from datetime import datetime
def show_datafr1():
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
print("Time =", current_time)
schedule.every(30).seconds.do(show_datafr1)
while True:
schedule.run_pending()
time.sleep(1)
The above code working fine. I am getting correct time every 30 seonds.
(Script run on google colab)
Problem is,
When I clicked stop and click run again. It actually run the script in two times.
like,
I clicked run script at 01second, (few seconds minutes later) I clicked stop.
If now I clicked run, said at 11 second, then it run as new schedule.
I am getting time at 01, 11, 31, 41 seconds in same script.
Can stop be really terminate the script? or any workaround?
or Can I resume it as resume the same script time??
I tried toolbar "runtime","restart runtime", every !pip need to reinstall again.
Thank you in advance.
I'm busy with an python script on a raspberry pi for a rain gauge.
The script need to count the tips of the bucket and write the total rain amount every 5 minutes to a csv file. The script does the writing now every 299.9 seconds but I want it to write every exact 5 minutes, for example: 14:00, 14:05, 14:10 and so on.
Is there anyone who could help me out?
Thanks in advance!
Use a cronjob, for raspberry pi go with crontab
https://www.raspberrypi.org/documentation/linux/usage/cron.md
You will find lots of helpful functions in the datetime module:
from datetime import datetime, timedelta
# Bootstrap by getting the most recent time that had minutes as a multiple of 5
time_now = datetime.utcnow() # Or .now() for local time
prev_minute = time_now.minute - (time_now.minute % 5)
time_rounded = time_now.replace(minute=prev_minute, second=0, microsecond=0)
while True:
# Wait until next 5 minute time
time_rounded += timedelta(minutes=5)
time_to_wait = (time_rounded - datetime.utcnow()).total_seconds()
time.sleep(time_to_wait)
# Now do whatever you want
do_my_thing()
Note that when do_my_thing() is called it will actually be fractionally after the exact time in time_to_round, because obviously computers can't do work in precisely zero time. It's guaranteed not to wake up before that time though. If you want to refer to the "current time" in do_my_thing(), pass in the time_rounded variable so that you get neat timestamps in your log file.
In the code above I've deliberately recomputed time_to_wait each time, rather than just setting it to 5 minutes after the first time. That's so that the slight delay I just mentioned don't gradually snowball after you've been running the script for a long time.
I'm trying to use the Schedule module to run a task during specific days of the week and specific hours, basically business hours. The while loop will work when the condition is true but once it's false it will not run again to see if the time frame still applies. I would have to restart the script for it to work.
I'm pretty new to Python and self taught. This is my first time posting here so please correct me if I've formatted this badly or haven't included enough information. I've tried scouring the forums to get around this particular issue I'm having but haven't found an answer; I'm probably searching wrong. It may be a simple issue but I've been wracking my brain for a few days. This is a small test portion of code that I'm trying to use for another script. Other people have recommended Cron but since this is going into a larger script, I only need a section of it to run on a task and not the whole thing.
from datetime import datetime as dt
import schedule
import time
def weekdayJob(x, i=None):
week = dt.today().weekday()
if i is not None and week < 5 and dt.now().hour in range(9,17):
schedule.every(i).minutes.do(x)
def printJob():
timestamp = time.strftime("%Y%m%d-%H%M")
print(f"test {timestamp}\n")
weekdayJob(printJob, 5)
while True:
schedule.run_pending()
time.sleep(5)
I've also tried
from datetime import datetime as dt
import schedule
import time
def weekdayJob(x, i=None):
week = dt.today().weekday()
if i is not None and week < 5 and dt.now().hour in range(9,17):
schedule.every(i).minutes.do(x)
def printJob():
timestamp = time.strftime("%Y%m%d-%H%M")
print(f"test {timestamp}\n")
x = 1
while x == 1:
weekdayJob(printJob, 1)
time.sleep(5)
while True:
schedule.run_pending()
time.sleep(5)
I figured that putting the scheduled job in the while loop would make it constantly check to see if the conditional statement was true but that doesn't seem the case. How would I make it so this script is constantly checking if weekdayJob is within the desired time frame so I don't have to restart the script.
Move the conditional statement into the printjob function, and do not use nested while loop (code here switches between business hours and non business hours). schedule tasks run continuously, but your function if-statement only runs during your defined business hours. Here running at 1minute interval (testing odd vs even minutes), you can spec your own business hours:
import datetime as dt
import schedule, time
from datetime import datetime
def printJob():
week = dt.datetime.today().weekday()
timestamp = time.strftime("%Y%m%d-%H%M")
if week < 5 and datetime.now().minute % 2 ==0: # in range(9,17):
print(f"business hours test...EVEN minutes... {timestamp}\n")
# your business hours function here...
else:
print(f'go home...test... ODD minutes... {timestamp}\n')
schedule.every(1).minute.do(printJob)
while True:
schedule.run_pending()
I am trying to count how long a very long process is taking:
import datetime
def main(argv):
starttime = datetime.datetime.now()
for f in somearray:
doSomething(f)
endtime = datetime.datetime.now()
deltatime = endtime-starttime
print "Operation took " + str(deltatime.seconds) + " seconds"
def doSomething(f):
# this takes a looong time (~10 minutes)
In the code above I only end up getting the time elapsed for the last time doSomething was run. I used to have doSomething as part of the main function and the timing was fine, but it made sense to move it to its own function.
I saw this question but it seems to serve a different need.
What am I doing wrong?
Thanks
What is the error you are getting? datetime doesn't have a .seconds attribute but it does have a .second attribute. maybe try str(deltatime.second) in your code.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the best way to repeatedly execute a function every x seconds in Python?
Hi so here is the code I have:
client = myclient(info1,info2)
sellor()
Contractor()
It works perfectly but what I would like to do is to make python launch that code every 60 seconds indefinitely...
I don't actually understand how I have to put the code together with the time loop
Any help is appreciated
Thank's
If the 60 seconds ignores the time it takes to execute your code):
from time import sleep
while True:
sleep(60)
# your code here
but if the 60 seconds takes into account the time it takes to execute your code:
from time import sleep
from os import fork
while True:
sleep(60)
fork() # create child process
# your code here
Use the sleep method. Just create a loop (while, for, whatever) and sleep for 60 secs every iteration.
import time
while True:
client = myclient(info1,info2)
sellor()
Contractor()
time.sleep(10)
hope it works,all the best mate
import time
repeat_time = 3.0
while True:
start_time = time.time()
# Your code goes here
time.sleep(max(repeat_time - (time.time() - start_time), 0.0))
And your code will be executed exactly every "repeat_time"
You could use sleep as already mentioned. But because there may be a variable amount of time needed for your own functions to run, this wouldn't necessarily mean your functions are run every 60 seconds.
If it was important that the period between each start of your functions is closer to 60 seconds, you could use time. I haven't tried this but something like
import time
while True:
# Get the current time
startTime = time.time()
# Your functions
client = myclient(info1,info2)
sellor()
Contractor()
delay = True
while delay:
if time.time() - startTime > 60:
delay = False # Break the delay
You might also think of just scheduling the task through windows scheduler. The benefit here would end the script once run and then execute the script again after scheduled interval. In the second approach it seems that the script instance process would continually run and only use the sleep function to do nothing for the specified time. I take it this way if the scripts fails at any instance you might have to keep a check to restart the script. While as a scheduled activity the script will be executed in any case at that specified intervals.
You might also not want the process thread to be kept running for the python script executed. I will research on this and you might get to hear form our other folks in the mean while.
Regards,
Harshal