How to run a python script at a specific time(s) - python

I'd like to write a simple python script for doing a specific job. I'm getting some time and link information from a web site.
times=
[
('17.04.2011', '06:41:44', 'abc.php?xxx'),
('17.04.2011', '07:21:31', 'abc.php?yyy'),
('17.04.2011', '07:33:04', 'abc.php?zzz'),
('17.04.2011', '07:41:23', 'abc.php?www'),]
What is the best way to click these links at the right time? Do I need to calculate the time interval between the current and the one in list and sleep for a while?
I'm really stuck at this point and open to any ideas which could be useful.

Take a look at Python's sched module.

you can use schedule module and it is easy to use and will satisfy your requirement.
you can try something like this.
import datetime, schedule, requests, time
TIME = [('17.04.2011', '06:41:44', 'abc.php?xxx'),
('17.04.2011', '07:21:31', 'abc.php?yyy'),
('17.04.2011', '07:33:04', 'abc.php?zzz'),
('17.04.2011', '07:41:23', 'abc.php?www')]
def job():
global TIME
date = datetime.datetime.now().strftime("%d.%m.%Y %H:%M:%S")
for i in TIME:
runTime = i[0] + " " + i[1]
if i and date == str(runTime):
requests.get(str(i[2]))
schedule.every(0.01).minutes.do(job)
while True:
schedule.run_pending()
time.sleep(1)
I have use request module and get method to call those URL. You can write whichever methods suits you.

This may help: How do I get a Cron like scheduler in Python? It is about cron-like scheduling in Python. And yes, it is based on sleeps.

I finally made and used this.
import time,datetime
def sleep_till_future(f_minute):
"""The function takes the current time, and calculates for how many seconds should sleep until a user provided minute in the future."""
t = datetime.datetime.today()
future = datetime.datetime(t.year,t.month,t.day,t.hour,f_minute)
if future.minute <= t.minute:
print("ERROR! Enter a valid minute in the future.")
else:
print "Current time: " + str(t.hour)+":"+str(t.minute)
print "Sleep until : " + str(future.hour)+":"+str(future.minute)
seconds_till_future = (future-t).seconds
time.sleep( seconds_till_future )
print "I slept for "+str(seconds_till_future)+" seconds!"

Related

How to Display Time (not static) in python?

Alright,the problem is i'm trying to build a personal assistant with my amateur skills.
I want to display the time which should be running and not be static.
This is what you wanted ? create a endless loop (Since you didn't mention in what situation the loop will end, I assume it will run infinitely until you manually end it) and print() with end='\r' (replace prev print) and pause and refresh every second
import time
import datetime
while True:
now = datetime.datetime.now()
print(f"Current Date and Time: {now} ", end='\r')
time.sleep(1)

How to make datetime constantly check the time and send a message in discord.py

So I want my discord bot to send out a message in the server every morning at 7 am. Using my variable time which is:
time = datetime.datetime.now()
and doing time.hour and time.minute, I can make it print something at the time i want using:
if time.hour == 7:
print('Its 7 am')
but using a whle statement datetime doesnt actually refresh the time. Second of all if there are any discord.py people how would i send the message without using an event refernec or command?
This should do what you want.
time = datetime.datetime.now
while True:
if time().hour == 7 and time().minute == 0:
print("Its 7 am")
sleep(60)
The reason the time doesn't actually refresh in your code is that you are storing the result of a function in the variable, not the function itself. If you don't include the parenthesis then the function gets stored in the variable so it can be called later using variable().
This question could already be answered on the following link:
Python - Start a Function at Given Time
Given the following information:
Reading the docs from http://docs.python.org/py3k/library/sched.html:
Going from that we need to work out a delay (in seconds)...
from datetime import datetime
now = datetime.now()
Then use datetime.strptime to parse '2012-07-17 15:50:00' (I'll leave the format string to you)
# I'm just creating a datetime in 3 hours... (you'd use output from above)
from datetime import timedelta
run_at = now + timedelta(hours=3)
delay = (run_at - now).total_seconds()
You can then use delay to pass into a threading.Timer instance, eg:
threading.Timer(delay, self.update).start()
You could take a look at https://schedule.readthedocs.io/en/stable/
Install schedule with pip:
$ pip install schedule
You could do something like that:
import schedule
import time
def job():
print("Its 7 am")
schedule.every().day.at("07:00").do(job)
while True:
schedule.run_pending()
time.sleep(1)

How to update a timestamp taken from server?

I have a very simple Python script in which I'm trying to print an updated timestamp (taken from a server by APIs) every n seconds.
After importing a custom module (FinexAPI) and the time module:
import FinexAPI
import time
and setting up the variable to get the server timestamp:
ticker = FinexAPI.ticker()
when = float(ticker['timestamp'])
if I perform:
print when
I'm getting the timestamp up to date. If I perform it again, I can see a new updated timestamp. Untill now there's no problem at all.
Now let's suppose I need to perform an "updated timestamp print" every 5 seconds:
def getNewTimestamp():
print when
time.sleep(5)
while True:
getNewTimestamp()
But with this code I'm getting the same timestamp every 5 seconds. I suppose the problem is that I'm defining when outside the getNewTimestamp function, so it basically keeps printing the same non-updated timestamp. But even if I define it inside the function I still get no update on the timestamp.
Another thing I'm thinking about is that while loop is not the best choice in this scenario, but that would be another story (I think...). Can someone help me figuring out what am I doing wrong and what is the best way to obtain and print the updated timestamp every 5 seconds?
You have to call the API in the loop:
def getNewTimestamp():
ticker = FinexAPI.ticker()
when = float(ticker['timestamp'])
print when
while True:
getNewTimestamp()
time.sleep(5)

How to use datetime to calculate duration and stop time?

I'm using Python 2.7 and want to use the datetime functions to calculate a user defined time to run a small pump. I know I'm missing something obvious but I've searched until I can't see straight. I have a textCtrl that the user will enter the minutes he wants the pump to run. Then a button click will start the scheduler and check to see if it's time to turn off the pump:
def timedPump(val):
now = datetime.datetime.now()
timeOff = now + datetime.timedelta(minutes=int(val))
if timeOff > now:
print 'pumpOn'
else:
print 'pumpOff'
return True
The problem is that datetime.datetime.now() updates everytime. How do I make it so that now = the time that the button was clicked?
This would be my solution to the problem:
from time import sleep
def pumpcheck(timer_in_minutes):
time_clicked = datetime.datetime.now()
now = time_clicked
timeDiff = datetime.timedelta(minutes=int(timer_in_minutes))
while (time_clicked + timeDiff > now):
print 'pumpOn'
now = datetime.datetime.now()
sleep(2)
print 'pumpOff'
It saves the time when the button was pushed and then checks in a loop, if the time is rfeached, if not, it update the current time, says pump is still on and sleep for a little while to not bloack cpu recources. When the time is reached, it says pumpoff
There is some information missing as to how timedPump is evaluated. I guess it's a simple loop.
What needs to happen is there have to be two functions, one that sets a turnOff-time and one that evaluates weather to turn on / off the pump.
This can be implemented as two methods of a class:
class PumpControl(object):
def setTime(self, val):
now = datetime.now()
self.timeOff=now + timedelta(minutes=int(val))
print 'pumpOn'
def checkTime(self):
if self.timeOff < datetime.now():
print 'pumpOff'
This way you would create a PumpControl object and then repeat checkTime:
controller = PumpControl()
#inside your loop
controller.checkTime()
#when you want to set the time
controller.setTime(val)
This should work across threads as well, so you can have one thread repeating and another asking for the time.
This sounds like something outside the scope of a single function. Either split the logic into two functions, or use a class to preserve start_time

How can I repeat something for x minutes in Python?

I have a program (temptrack) where I need to download weather data every x minutes for x amount of hours. I have figured out how to download every x minutes using time.sleep(x*60), but I have no clue how to repeat this process for a certain amount of hours.
UPDATE:
Thank you to everyone who posted a solution.
I marked the example using "datetime.datetime.now() + datetime.timedelta(hours=x)" as the best answer because I could understand it the best and it seems like it will work very well for my purpose.
Compute the time you want to stop doing whatever it is you're doing, and check each time that the time limit hasn't expired. Like this:
finish_time = datetime.datetime.now() + datetime.timedelta(hours=6)
while datetime.datetime.now() < finish_time:
do_something()
sleep_for_a_bit()
I've just found sched in the Python standard library.
You are looking for a scheduler.
Check this thread.
May be a bit of overkill, but for running background tasks, especially if you need a GUI, I'd recommend checking out the PyQt route with QSystemTrayIcon and QTimer
Maybe I'm misunderstanding you, but just put it in a loop that runs a sufficient number of times. For example, to download every 5 minutes for 2 hours you need to download 24 times, so:
for i in range(24):
download()
sleep(5*60)
If you need it to be parameterizable, it's just:
from __future__ import division
from math import ceil
betweenDLs = 5 # minutes
totalTime = 2*60 # minutes
for i in range(int(ceil(totalTime/betweenDLs))):
download()
sleep(betweenDLs*60)

Categories

Resources