Run command on complex schedule in python - python

I know there are a lot of schedule and event libraries out there but I haven’t found one where I can make complex schedule. E.g
run python command every 500ms between 7.55 and 8.05 on Monday-Friday
Anyone who can easily crack that task in Python? I have considered using schedule but as far as I can tell then I can’t add something like every 500 ms. Although I do believe in a cron-like approach (except cron only allows down to every minute).
I’m thinking of calculating next “cron” time and then use sched to execute the command with the calculated delay. No idea how to calculate something like that though. I could someone already cracked this challenge though.

Turns out the apscheduler supports exactly what I'm looking for.

Related

How to get function to run at specyfic time using python and PyQt not using Cron

I'm creating RSS app in PyQt and I'm trying to find a good way to program updates. I found this Executing periodic actions in Python but maybe there is Qt specific way to do this things.
I know update period for each feed so I want to run update at specific time(hh:mm).
Making 10 minute loop that will check current time and run a update if its grater than next predicted feed update seems missing the point of knowing specific time to run it.
You should use QTimer in Qt applications. Usually you don't need to care about specific update time, as the goal is regular periodic check. So the most straightforward approarch is to create a timer for each feed and set the update interval of each timer (e.g. 10 minutes).
If you for some reason really want to make an update at specific time, you can use something like QDateTime::currentDateTime().msecsTo(targetTime) to calculate timer interval, use QTimer::setSingleShot to make the timer non-periodic and set another timer when the first one is expired.
It may be reasonable to do timer->setTimerType(Qt::VeryCoarseTimer) because you don't need much accuracy and Qt can optimize performance and power consuming in some cases.
Note that you generally cannot use Python's means to set up timers because Qt has its own event loop and won't allow other libraries to run something in the middle of it.

Calling a function at datetime in Python

What is a good way to call a function at datetime in Python?
There 3 ways that I know of:
"Are we there yet?!" (check at if date has passed at interval (time.sleep(interval)))
This is obviously bad. It can only be precise if interval is low, which becomes inefficient.
Sleep off the difference (time.sleep(timedelta.seconds))
This is better, but I don't like the idea of putting a thread to sleep for an insanely long time, e.g. 6 months if such is the date.
Hybrid between the two above; sleep off the difference if difference is bellow interval. If above, sleep for an interval to prevent long sleeps.
I think this is the best out of all three when you think about long sleeps, but interval seems bad anyway.
Are there any more ways you can think of? Is there anything in standard library that can help me call a function at datetime behind the scene?
EDIT:
I'm asking this because I've actually developed my own Cron implementation in Python. The only problem is that I can't decide how my code should wait for next occurrence. One of the differences between my implementation and original Cron is support for seconds. So, simply sleeping for minimum possible interval (1 second in my case) is too inefficient.
I realize now that this question could perhaps be changed to "how does Cron do this?" i.e. "how does Cron check if any date has passed? Does it run constantly or is a process run each minute?". I believe the latter is the case, which, again, is inefficient if interval is 1 second.
Another difference is that my code reads crontab once and calculates the exact date (datetime object) of next occurrence from the pattern. While Cron, I assume, simply checks each minute if any pattern from crontab matches current time.
I'll stick to the "hybrid" way if there's no other way to do this.
If this is something that might be six months out like you said, a chron job is probably more suitable than keeping a python program running the whole time.
I use the gobject main loop, but any library with an event loop should have this ability.
It might be a good idea to use a cron job.
you can edit the cron table with : crontab -e
and add a line like this (called every 20 minutes)
*/20 * * * * /usr/bin/python /home/toto/my_script.py

How to periodically check for the current date from within a program?

I would like to write a tiny calendar-like application for someone as a birthday present (to be run on Ubuntu). All it should do is display a separate picture each day, so whenever it's invoked it should check the date and select the appropriate picture from the collection I would provide, but also, in case it just keeps running, it should switch to the next picture when the next day begins.
The date-checking on invocation isn't the problem; my question pertains to the second case: how can I have the program notice the beginning of the next day? My clumsy approach would be to make it check the current date at regular intervals and let it change the displayed picture once there was a change in date, but that strikes me as very roundabout and not particularly elegant.
In case any of you have got some idea of how I could accomplish this, please don't hesitate to reply. I would aim to write the application in either Perl or Python, so suggestions concerning those two languages would be most welcome, but any other suggestions would be appreciated as well.
Thanks a lot for your time!
The answer to this could be very system dependant. Controlling the time at which your program is executed is likely to be system dependant. On all *nix type systems, I would use cron. Assuming for a moment that you are using a *nix system, the answer then depends on what the program actually does.
If it only needs to select an image, then I would suggest that it not be run continuously, but terminates itself after selecting it, and is then run again the next day (there are a lot of tutorials on how to setup cron).
If, however, it has some form of UI and it is likely (read possible) to keep running for several days, then you can follow two approaches:
Create your program as it is, to poll periodically for the current time, and do a date delta comparison. Python timedelta objects could help here. This is pretty much your inelegant approach.
The other solution would be to send it a signal from cron when you do wish it to update. This process would mean that you would have to make it signal aware, and respond to something like USR1. The Python docs talk to this, but you can find many tutorials on the web. This approach also works quite nicely for daemonised apps.
I'm sure there are many other approaches too, but those are the ones that come to mind for a quickish and nastyish app.
Did you think about scheduling the invoke of your script?
For me, the best approach is this:
1.Have two options to run the script:
run_script
run_script --update
2.Schedule the update run in some task scheduler (for example Cron) to be executed daily.
3.When you would want to check the image for current day, simply run the script without update option.
If you would like me to extend any part of these, simply ask about it.

Render in infinity loop

Question for Python 2.6
I would like to create an simple web application which in specified time interval will run a script that modifies the data (in database). My problem is code for infinity loop or some other method to achieve this goal. The script should be run only once by the user. Next iterations should run automatically, even when the user leaves the application. If someone have idea for method detecting apps breaks it would be great to show it too. I think that threads can be the best way to achive that. Unfortunately, I just started my adventure with Python and don't know yet how to use them.
The application will have also views showing database and for control of loop script.
Any ideas?
You mentioned that you're using Google App Engine. You can schedule recurring tasks by placing a cron.yaml file in your application folder. The details are here.
Update: It sounds like you're not looking for GAE-specific solutions, so the more general advice I'd give is to use the native scheduling abilities of whatever platform you're using. Cron jobs on a *nix host, scheduled tasks on Windows, cron.yaml on GAE, etc.
In your other comments you've suggested wanting something in Python that doesn't leave your script executing, and I don't think there's any way to do this. Some process has to be responsible for kicking off whatever it is you need done, so either you do it in Python and keep a process executing (even if it's just sleeping), or you use the platform's scheduling tools. The OS is almost guaranteed to do a better job of this than your code.
i think you'd want to use cron. write your script, and have cron run it every X minutes / hours.
if you really want to do this in Python, you can do something like this:
while(True):
<your app logic here>
sleep(TIME_INTERVAL)
Can you use cron to schedule the job to run at certain intervals? It's usually considered better than infinite loops, and was designed to help solve this sort of problem.
There's a very primitive cron in the Python standard library: import sched. There's also threading.Timer.
But as others say, you probably should just use the real cron.

Can I damage the system by running time.sleep() with this newbie code in Python?

Im sure there is a better way to do this, but I am quite the newbie so I did it the only way I could figure it out. The thing is, I have a script that updates a textfile with the newest posts from an RSS feed (I got some help from you guys to figure it out). But I want this script to be automated, so I made this:
import time
import os
seconds = 3600
kjor = 'python vg.py'
time.sleep(seconds)
os.system(kjor)
time.sleep(seconds)
os.system(kjor)
time.sleep(seconds)
os.system(kjor)
I continued with copying those 24x downwards. I know this problably can be done alot better with some loop (while?), but Im afraid I dont have alot of knowledge in that field (yet).
My question, however, is as following: Can the system be damaged in any way if I let this run over a longer period of time?
To answer your question, no, this won't hurt anything. While the time.sleeps are sleeping, the program will take very little processing power and the rest of the system can run normally.
Now, as for your looping issue. If you want the code run forever (or until you stop the program) the code you want is
while True:
os.system(kjor)
time.sleep(seconds)
This is, literally, and infinite loop, but in this case that (is probably) what you want.
If you are attached to having a particular number of iterations, then you could do something like sunqiang's answer (repeated here)
for loop in xrange(240):
os.system(kjor)
time.sleep(seconds)
Finally, if you are on a Unix platform (such as Linux or Mac) you should take a look at cron, as it is designed to set up recurring programs to run and particular time periods. You could set it up to run your script every minute and it will happily do so until the end of time (or you remove it, whichever comes first).
Use xrange please, don't copying your code 24x times.
for loop in xrange(240):
time.sleep(seconds)
os.system(kjor)
It will not damage your system, as far as I know.
It does not damage any system and it is pretty common as well.
Just create a loop so as your application will gently stop running after some time;
Or better yet, make it check for a condition, maybe listen to a tcp port waiting for someone to ask it to quit (then you'll need to create a second application to send this quit message).

Categories

Resources