So I need my program to run a task every given hour of a given day, I looked for a module that could easily do it and it exists, the schedule one, unfortunately we do not have it at my company's computer and I am not allowed to install anything, so I thought of something like this as a solution
import datetime
now = datetime.datetime.now()
while True:
if now.strftime("%d") == '09':
if now.strftime("%H") == '18':
do something
but it does not quite work as expected, if i Run the program at the schedulled time it runs normally, but if it's not, it does nothing when the time comes
what can I do?
You've defined now outside the loop at the start of the program. Once running, it never changes. Set now inside the loop, and consider using sleep to let this program not waste resources as much.
Related
So I am making a website, and something that required for part of the security is having a waiting period when trying to do something, for example trying to delete something, this would help incase someone's account was stolen and someone tried to ruin their account.
I'm already using SQLite so I'm going to create a table in there where scheduled events will be defined.
What I'm wondering is what is the best way to constantly check these scheduled events, it may also be important to note I want to check at least every hour. My immediate thought was creating a separate thread and running a function on there with a while loop in it which will constantly run a chunk of code with a time.sleep(3600) at the end of the function, like this:
def check_events(self):
while True:
# code
time.sleep(3600)
I'm not sure though if this is the most efficient way of doing it.
That function currently is inside my website code class hence the self, is that something I need to put on the outside or no?
I would either create a cron job on your server (which is the most straightforward)
or use a schedule module to schedule your task, see example:
import time
import schedule
from sharepoint_cleaner import main as cleaner
from sharepoint_uploader import main as uploader
from transfer_statistics import main as transfer_stats
schedule.every(1).hours.do(uploader)
schedule.every(1).hours.do(transfer_stats)
schedule.every().sunday.do(cleaner)
while True:
schedule.run_pending()
time.sleep(10)
https://github.com/ansys/automatic-installer/blob/4d59573f8623c838aadfd49c312eeaca964c6601/sharepoint/scheduler.py#L3
I wrote a python script which makes calculation at every hour. I run this script with crontab scheduled for every hour. But there is one more thing to do;
Additionally, I should make calculation once a day by using the results evaluated at every hour. In this context, I defined a thread function which checks the current time is equal to the specified time (15:00 PM, once a day ). If it is, thread function is called and calculation made.
What I wanna ask here is; is this approach applicable ? I mean, running the first script at every hour using crontab, and calling the second function using thread function once a day.
Is there any other way of doing this ?
You may use python library sched.
It efficient way to schelude your operations.
You could do a script which runs all the time and just sleeps for one hour.
import time
hours_ran = 0
while True:
# your stuff here
time.sleep(3600)
hours_ran += 1
if hours_ran == 24:
# calculate stuff
hours_ran = 0
This is not necessarily better tho...
You can setup systemd to manage this process.
This question already has answers here:
How to repeatedly execute a function every x seconds?
(22 answers)
Closed 7 years ago.
I have a requirement where I need to run a task for every 5 seconds, but only between specific times (like between 1:30 and 2:30 tomorrow).
I looked at celery, but a normal task cannot be executed repeatedly in celery and the periodic tasks cannot be dynamically scheduled.
I also looked at APScheduler, but that doesn't support running it as a 'daemon' and scheduling tasks from outside.
Any idea what I could use to make this happen?
Edit: Should have mentioned this earlier, I need to do this during a web request, like a background task.
If I understood your question right, Maybe like this ?
from time import sleep
from datetime import datetime
if 90 <= datetime.now().hour * 60 + datetime.now().minute <= 150:
# Do something
time.sleep(5)
I converted hour to minute to handle the time easier. So 90min is 1.30 and 150min is 2.30. (Considered AM)
And the time module make this run at 5 second intervals.
If you also need days, you can implement that easily by;
datetime.now().day
And you need to put this into a loop for the condition to be continuously tested. The sleep method I used will result in checking every 5 seconds.
As you added the code can't be blocking the process. Another way could be using division method. Something like;
While #condition:
if not datetime.now().second % 5:
# Process
But of course I must add that this is a bad solution given that it always runs. So I am sure using an appropriate library will be more helpful, which is not in my knowledge at the moment.
I think #Rockybilly's answer is pretty close if you would like an entirely python specific answer. However, you will need to wrap that in a:
While True:
##Rockybilly's if statement
This is needed in order to repeat the process. You'd also like to incorporate something as seen here:
delay a task until certain time
You would do this once outside of your specified range (2:31 for instance), and then sleep the script until 1:30 the next day. This will help to ensure it's not constantly running.
As people have commented, you can do this, in some capacity, using either CRON (Unix) or Task Scheduler (Windows)
--
Since you have edited your question, I will add a response to that edit here. Please see my comment below, in response to #Rockybilly, as this is something you may want to clarify.
You may want to look into the threading, multiprocessing, or the new asyncio modules if these need to run in parallel.
(Can't link Asyncio due to rep restraints)
There is a significant difference between my question and the given one. If I implement sleep as given on the link (which some people think my question is a duplicate of another one) then my whole app will hang for certain time. On the other hand I am looking for a scheduler so that my app will not hang but just after a certain period of time a .wav file will run. Meanwhile I would be able to do anything using my app. Hope that makes sense.
I am going to build an alarm clock. I think I can do this according to this Algorithm...
take current time using time.clock()
compare current time with the given time.
if current time is not given time then continue taking current time and compare whether current time is the given time or not.
if current time is the given time then play the .wav file.
The problem with this program is it will continuously run until the given time. So I am looking for better idea. Let's say if there is any Python module/class/function which can play a sound file on a given time. Is there any Python module/class/function which can wake up on a given time? Or my algorithm is used usually for all alarm clocks?
As far as I know there is not a good Python module to do this. What you are looking for though is a cron job. It allows you to schedule specific scripts to run at certain times. So your Python script would end up just being the code to play the .wav, and then you would need to create a cron job to tell your computer to execute that script at a certain time each day.
Have a look at the sched module.
Here's an example on how to use it:
import sched, time, datetime
def print_time():
print("The time is now: {}".format(datetime.datetime.now()))
# Run 10 seconds from now
when = time.time() + 10
# Create the scheduler
s = sched.scheduler(time.time)
s.enterabs(when, 1, print_time)
# Run the scheduler
print_time()
print("Executing s.run()")
s.run()
print("s.run() exited")
The time is now: 2015-06-04 11:52:11.510234
Executing s.run()
The time is now: 2015-06-04 11:52:21.512534
s.run() exited
I want to schedule a job (run a python script) everyday at a specific time till a specific date has been reached.
Researching on a lot of Pythonic schedulers, I thought that APScheduler was a good candidate to get around this.
This is an example snippet using APScheduler that starts a job and executes it every two hours after a specified date.
from datetime import datetime
from apscheduler.scheduler import Scheduler
# Start the scheduler
sched = Scheduler()
sched.start()
def job_function():
print "Hello World"
# Schedule job_function to be called every two hours
sched.add_interval_job(job_function, hours=2)
# The same as before, but start after a certain time point
sched.add_interval_job(job_function, hours=2, start_date='2010-10-10 09:30')
How to achieve the same and have a upper limit date after which the job should not be executed?
Any suggestions that revolve within and outside the APScheduler are most welcome.
Thanks in advance.
Use a cron job that executes your script every two hours (cron is made specifically for things like this). In your script, you just look up the system date and check, if it's smaller than your given date. If it's smaller, you execute the rest of your script, otherwise you quit.
You may also write additional code, so you get notified when the script is not actually executed anymore.
I eventually found the interval trigger can take an end_date.
You can pass arguments for the trigger to add_job with trigger='interval':
sched.add_job(job_function, trigger='interval', hours=2, end_date='2016-10-10 09:30')
I think you may be using an older version of the software.