How can I run my code at a specific time? [duplicate] - python

This question already has answers here:
How do I get a Cron like scheduler in Python?
(9 answers)
Closed 1 year ago.
I am developing a software with python. And I want my code to run at certain hours. It will run once every 5 minutes without a break. But I want it to work exactly at certain hours and minutes. For example, such as 20:00, 20:05, 20:10...
I used time.sleep(300) but if for example 5 seconds passes after my program runs, it starts to delay 5 seconds in each run and for example it starts running 1 minute late after 12 runs. For example, it should work at 20:05, but it starts at 20:06.
How can I provide this?

You can use schedule module
import schedule
import time
from datetime import datetime
now = datetime.now()
def omghi():
print("omg hi there xD")
schedule.every(5).minutes.do(omghi)
while True:
schedule.run_pending()
time.sleep(1)

There is a useful model for that case.
It is an external model, you have to download it using pip and it is called
schedule
https://pypi.org/project/schedule/ - here you can see all the details.

I believe that using timed threads works the best with what you want. This excellent answer uses threading.Timer from the library threading as follows:
import threading
def printit():
threading.Timer(5.0, printit).start()
print "Hello, World!"
printit()

Thank you very much for the answers. But this is how I handled it and I wanted to share it with you :)
import time
from datetime import datetime
while True:
now = datetime.now()
if (now.minute % 5) == 0 and now.second == 0:
print("Fire!")
time.sleep(1)

Related

Scheduling a job in Python

I wish to schedule a python script for every 30 minutes. I am currently using the Timer to run the python script but it is not working precisely. I am using Linux. This code works fine on windows but is not working correctly on Linux. It should be triggered after half an hour but it gets triggered within a minute.
from datetime import datetime, timedelta
from threading import Timer
j=1
while True :
x=datetime.today()
y = x + timedelta(minutes=10*j)
print(y)
delta_t=y-x
secs=delta_t.seconds + 1
def hello_world():
print ("hello world")
print("yes)")
t = Timer(secs, hello_world)
t.start()
j=j+1`
Can anyone point out the mistake in above code or suggest an alternative to run the python script in linux after every 30 minutes?
Thank you
You could use Python’s schedule library.
import schedule
def hello_world():
print ("hello world")
print("yes)")
schedule.every(30).minutes.do(hello_world)
while True:
# Checks whether a scheduled task
# is pending to run or not
schedule.run_pending()
Further information: https://www.geeksforgeeks.org/python-schedule-library/

Run function at a specific time in python [duplicate]

This question already has answers here:
Start a Function at Given Time
(9 answers)
Closed 3 years ago.
import time
import webbrowser
print(time.ctime())
targetTime = time.ctime()
if(targetTime == "Tue May 01 11:05:17 2018"):
webbrowser.open("https://www.youtube.com/watch?v=dQw4w9WgXcQ")
This is what I tried already and it doesn't open the link when the time comes. I read through the time library but I couldn't find anything to help me. My target is for the program to open a link at a time that I want. Any help appreciated.
Python comes built-in with a simple scheduling library called sched that supports this.
import sched, time
def action():
webbrowser.open("https://www.youtube.com/watch?v=dQw4w9WgXcQ")
# Set up scheduler
s = sched.scheduler(time.localtime, time.sleep)
# Schedule when you want the action to occur
s.enterabs(time.strptime('Tue May 01 11:05:17 2018'), 0, action)
# Block until the action has been run
s.run()
If you don't mind using third party modules, there's Python pause:
import pause
from datetime import datetime
pause.until(datetime(2018, 5, 1, 11, 5, 17))
webbrowser.open("https://www.youtube.com/watch?v=dQw4w9WgXcQ")

Timers in Python [duplicate]

This question already has answers here:
How to repeatedly execute a function every x seconds?
(22 answers)
Closed 6 years ago.
I'm working on a problem where I need to print something every 45 seconds. So I have used time.sleep(45) and made up the code as below:
import timer
def print_data():
print "Hello World!"
time.sleep(45)
while True:
print_data()
I have a couple of queries which I'm trying to understand and learn. I have re-searched this but couldn't get a answer I'm looking for. Please find my queries below:
How do I print the above content continuously exactly for 1 hour waiting every 45 sec?
Can we give a random value say, 30-45 seconds waiting time. So it can wait for any value between 30-45 seconds ?
How does RAM or CPU behave when I put on the timer for 4 -5 hours refreshing/waiting every 60 seconds ? Does this effect the CPU or RAM in any way ?
Kindly help me in understanding these questions. Any help would be appreciated. Thanks in advance.
This should do what you are looking for:
import time
from random import randint
def print_data():
print "Hello World!"
time.sleep(randint(30, 45))
def print_data_for(total_time):
start_time = time.time()
while time.time() < start_time + total_time:
print_data()
print_data_for(60*60) # 1 hour
As for the CPU/RAM usage, my experience (I have a script based on sleep that prints regular status messages monitoring another process) is that the process is not very expensive at all while it is idling about, which is confirmed here: Python - is time.sleep(n) cpu intensive?
You could print every random value of seconds, and wait for a keyboard interrupt because time.sleep() does nothing.
import time
from random import randint
def print_data(time, data):
start_time = time.time()
if time.time() < start_time + time:
pass
except KeyBoardInterrupt:
data = raw_input("what's your value?")
print data
else:
print data
data = "Hello World!"
while True:
print_data(data)
if time.time() - start_time > (60*5):
break
print "Done!"
Also to know your CPU and RAM usage, you can use the psutil library https://pypi.python.org/pypi/psutil, psutil is a module providing an interface for retrieving information on running processes and system utilization (CPU, memory) in a portable way by using Python, implementing many functionalities offered by tools like ps, top and Windows task manager.
It currently supports Linux, OS X, FreeBSD and Windows with Python versions from 2.4 to 3.1 by using a unique code base.

5 minutes loop in python does it causing issue?

I am using this loop for running every 5 minutes just creating thread and it completes.
while True:
now_plus_5 = now + datetime.timedelta(minutes = 5)
while datetime.datetime.now()<= now_plus_5:
new=datetime.datetime.now()
pass
now = new
pass
But when i check my process status it shows 100% usage when the script runs.Does it causing problem?? or any good ways??
Does it causes CPU 100% usage??
You might rather use something like time.sleep
while True:
# do something
time.sleep(5*60) # wait 5 minutes
Based on your comment above, you may find a Timer object from the threading module to better suit your needs:
from threading import Timer
def hello():
print "hello, world"
t = Timer(300.0, hello)
t.start() # after 5 minutes, "hello, world" will be printed
(code snippet modified from docs)
A Timer is a thread subclass, so you can further encapsulate your logic as needed.
This allows the threading subsystem to schedule the execution of your task such that it's not entirely CPU bound like your current implementation.
I should also note that the Timer class is designed to be fired only once. As such, you'd want to design your task to start a new instance upon completion, or create your own Thread subclass with its own smarts.
While researching this, I noticed that there's also a sched module that provides this functionality as well, but rather than rehash the solution, check out this related question:
Python Equivalent of setInterval()?
timedelta takes(seconds,minutes,hours,days,months,years) as input and works accordingly
from datetime import datetime,timedelta
end_time = datetime.now()+timedelta(minutes=5)
while end_time>= datetime.now():
statements

Python: Restrict the code to be run for an hour

I have written a scraper that does html scraping and then use API to get some data, since its a very lengthy code I haven't put it here. I have implemented random sleep method and using it within my code to monitor throttle. But I want to make sure I don't over run this code, so my idea is to run for an 3-4 hours then taker breather and then run again. I haven't done anything like this in python I was trying to search but not really sure where to start from, it would be great if I get some guidance on this. If python has a specific module link to that would be a great help.
Also is this relevant? I don't I need this level of complication?
Suggestions for a Cron like scheduler in Python?
I have functions for every single scraping task, and I have main method calling all those functions.
You can use a threading.Timer object to schedule an interrupt signal to the main thread after the time is exceeded:
import thread, threading
def longjob():
try:
# do your job
while True:
print '*',
except KeyboardInterrupt:
# do your cleanup
print 'ok, giving up'
def terminate():
print 'sorry, pal'
thread.interrupt_main()
time_limit = 5 # terminate in 5 seconds
threading.Timer(time_limit, terminate).start()
longjob()
Put this in your crontab and run every time_limit + 2 minutes.
You could just note the time you have started and each time you want to run something make sure you haven't exceeded the given maximum. Something like this should get you started:
from datetime import datetime
MAX_SECONDS = 3600
# note the time you have started
start = datetime.now()
while True:
current = datetime.now()
diff = current-start
if diff.seconds >= MAX_SECONDS:
# break the loop after MAX_SECONDS
break
# MAX_SECONDS not exceeded, run more tasks
scrape_some_more()
Here's the link to the datetime module documentation.

Categories