Run function at a specific time in python [duplicate] - python

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")

Related

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

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)

Python while loop be executed in time interval [duplicate]

This question already has answers here:
How do I make a time delay? [duplicate]
(13 answers)
Closed 2 years ago.
I wanted to use while loop to keep executing my script over and over but there is a problem as my code calls an API that doesn't allow so many calls in small time so I wanted to make the while loop be executed at time interval so I tried this code
from threading import Timer
def myfunc():
some code
while True:
t = Timer(1.0, myfunc)
t.start()
but it doesn't work, so is there any other way to do it correctly?
Use the time module:
import time
def myfunc():
some code
while True:
myfunc()
# unit is in second. Example below wait for 1 second before continuing
time.sleep(1)

Using sleep() to create a function that consistently loops every second [duplicate]

This question already has answers here:
How to repeatedly execute a function every x seconds?
(22 answers)
Closed 4 years ago.
I have a program that needs to execute every second. However I am concerned that the code would add a slight delay in turn causing it delay slightly longer then intended. Sample code:
while True:
print(time)
sleep(1)
In my case I will be adding more complicated function calls in this loop and am concerned that they will mess with my timer. Should I even be worried, and or is there another way for me to ensure this function loops every second?
You can use this:
import threading
def scheduleFunc():
threading.Timer(1.0, scheduleFunc).start()
print(time)
Or use this:
import sched, time
scheduled = sched.scheduler(time.time, time.sleep)
def scheduleFunc(sc):
print(time)
scheduled.enter(60, 1, scheduleFunc, (sc,))
scheduled.enter(60, 1, scheduleFunc, (scheduled,))
scheduled.run()

Timing python programs [duplicate]

This question already has answers here:
How do I get time of a Python program's execution?
(38 answers)
Closed 4 years ago.
So I am trying to see how long it takes my program to run, and the solution I came up with is:
import datetime
time1 = datetime.datetime.now()
[program code]
time2 = datetime.datetime.now()
print(time2 - time1)
I want to know if this is an efficient/correct solution, because all the guides I could find on the internet would use modules such as timeit, etc.
I would appreciate any feedback.
Yes, that works. However, another solution is:
import time
start = time.time()
# do stuff
print(time.time() - start)
You could also use time.clock() instead of time.time()

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.

Categories