run python program every 15 minutes when seconds are 0 [duplicate] - python

This question already has answers here:
Start a Function at Given Time
(9 answers)
Closed 1 year ago.
I have been writing this code and the time taken for the execution is about 3-4 seconds and I want it to run every 15 minutes I have been using this code
while True:
if datetime.datetime.now().minute % 15 == 0:
...
time.sleep(60)
now I cannot start the code to run exactly when the seconds on the clock are at 0 so I want the code to run exactly when the seconds are zero.
Thanks in advance

If you'll think about it - you're suspending your code for 60 seconds on time.sleep(60) but you're not considering the time it takes for the code to execute each time, which creates a time difference.
You could calculate the difference in time for the next execution to happen instead of constant 60
BTW, If you want to execute a code repeatedly you could use crontab to execute your scripts for you, it's simple and on-time so you won't need to worry about timings

Related

A general programming question: Is there a way to trigger a function every x seconds without remembering the last time it was triggered? [duplicate]

This question already has answers here:
How do I get a Cron like scheduler in Python?
(9 answers)
Closed last month.
Sorry if this is a basic question, but I want to have a function trigger every fixed amount of time, say 2 seconds. In general I would do something like:
lifetime = getCurrentTime
if (lifetime - lastTime > triggerTime)
doTheThing()
lastTime = lifetime
end
This normally works fine, but I'm working on a program where each object stores its own lifetime, and there could be hundreds of objects at once. I'm wondering if there's a way that each object wouldn't need to also remember its own lastTime -- I was thinking something with rounding or modulo, but even then you'd still need to remember how many times the function had triggered before.
I'm wondering if anyone knows of a good general way to have a trigger function every x seconds without having to remember the last time it triggered or how many times it's triggered?
Have you tried using sched yet? Here's a task done every 5 seconds to get you started:
import sched
import time
def doTheThing(runnable_task, every):
runnable_task.enter(every, 1, doTheThing, (runnable_task, every))
print("The thing...")
task = sched.scheduler(time.time, time.sleep)
every = 5
task.enter(every, 1, doTheThing, (task, every))
task.run()

make a function run every 5 minutes in python( no cron Job) [duplicate]

This question already has answers here:
Repeat python function at every system clock minute
(3 answers)
Sleeping for the remaining time
(2 answers)
Closed 5 months ago.
I wrote a script which fetchs stock prices, cleans it and stores it in excel file.
below code is an example
def fetchprice();
#fetchs stock price
#cleans it
while True;
fetchprice()
time.sleep(300)
so i right now i am making it sleep for 5 minutes to run every 5 minutes
but the problem is when the function runs it takes some seconds to complete the task and after sleeping for 5 minutes instead of running at 9:30 am it runs at 9:30:08 am adding seconds from the function time.
is there any way i can run the task exactly after 5 minutes for example: if i start at 9:30 next it should be at 9:35, 9:40, 9:45 not matter how many seconds the function takes.

Python - Pause entire script every 10 minutes

Need a way to pause a script for 2 minutes after letting it run for 10 minutes first, and then have this process repeat itself. I need the script itself to continue running throughout the 10 minutes.
I tried using threading but found that it didn't actually pause the the rest of the script.
EDIT: Added code to give perspective. Hopefully this helps to explain my issue.
Your code has a nice loop where you can implant the pause, like so:
from datetime import datetime, timedelta
...
def start():
lastsleep = datetime.now() # <-- new
while True:
openBank()
gear()
invCheck()
timer = random.uniform(33, 37)
print("Sleep time: %s" % timer)
time.sleep(timer)
if (datetime.now() - lastsleep) > timedelta(minutes=10): # <-- new
time.sleep(2*60)
lastsleep = datetime.now()
Note that this will not sleep exactly after 10 minutes, but whenever 10 minutes are over and it reaches the checkpoint. This may be 10:12 or 13:47 minutes, depending on what the other code (openBank(), gear() etc.) does before.
Answer before code was shown:
The problem is: we have no information on how your code looks like.
If you have
something = getSomething()
something.DoSomeVeryExpensiveOperation() # takes 25 minutes
there's no good way to interrupt or pause that method after 10 minutes.
The only way I can think of as a generic method is like this:
use multiprocessing
monitor the process from outside
after 10 minutes, suspend all threads of the process
sleep 2 minutes
resume all threads of the process
Before you do that, you should know why you should never suspend a thread

what is the unit of timeit() from python3 timeit module function [duplicate]

This question already has an answer here:
What unit of time does timeit return?
(1 answer)
Closed 4 years ago.
import time
import timeit
start = timeit.timeit()
time.sleep(5)
end = timeit.timeit()
time_elapsed = end - start
print(end)
print(time_elapsed)
print(start)
Outputs:
0.018255482330552297
-0.00033663523232263515
0.018592117562874932
As the documentation clearly says:
This… returns the time it takes to execute the main statement a number of times, measured in seconds as a float.
Meanwhile, notice that this is the elapsed time to run the main statement—that is, nothing at all, in your case. It's not a timestamp or anything like that. So subtracting end - start doesn't give you anything useful—it's the difference in elapsed time for two different runs of a no-op.

Job scheduling for data scraping on Python

I'm scraping (extracting) data from a certain website. The data contains two values that I need, namely (grid) frequency value and time.
The data on the website is being updated every second. I'd like to continuously save these values (append them) into a list or a tuple using python. To do that I tried using schedule library. The following job schedule commands run the data scraping function (socket_freq) every second.
import schedule
schedule.every(1).seconds.do(socket_freq)
while True:
schedule.run_pending()
I'm facing two problems:
I don't know how to restrict the schedule to run during a chosen time interval. For example, i'd like to run it for 5 or 10 minutes. how do I define that? I mean how to I tell the schedule to stop after a certain time.
if I run this code and stop it after few seconds (using break), then I often get multiple entries, for example here is one result, where the first list[ ] in the tuple refers to the time value and the second list[ ] is the values of frequency:
out:
(['19:27:02','19:27:02','19:27:02','19:27:03','19:27:03','19:27:03','19:27:03','19:27:03','19:27:03','19:27:03','19:27:04','19:27:04','19:27:04', ...],
['50.020','50.020','50.020','50.018','50.018','50.018','50.018','50.018','50.018','50.018','50.017','50.017','50.017'...])
As you can see, the time variable is entered (appended) multiple times, although I used a schedule that runs every 1 second. What i'd actually would expect to retrieve is:
out:
(['19:27:02','19:27:03','19:27:04'],['50.020','50.018','50.017'])
Does anybody know how to solve these problems?
Thanks!
(I'm using python 2.7.9)
Ok, so here's how I would tackle these problems:
Try to obtain a timestamp at the start of your program and then simply check if it has been working long enough each time you execute piece of code you are scheduling.
Use time.sleep() to put your program to sleep for a period of time.
Check my example below:
import schedule
import datetime
import time
# Obtain current time
start = datetime.datetime.now()
# Simple callable for example
class DummyClock:
def __call__(self):
print datetime.datetime.now()
schedule.every(1).seconds.do(DummyClock())
while True:
schedule.run_pending()
# 5 minutes == 300 seconds
if (datetime.datetime.now() - start).seconds >= 300:
break
# And here we halt execution for a second
time.sleep(1)
All refactoring is welcome

Categories