How to convert Schedule to APScheduler module? - python

I'm a python newbie and need a little help with my code.
I need to convert my code to use APSCHEDULER and not SCHEDULE module because I need to use hours, minutes, seconds which SCHEDULE is not capable of. How can I convert this script to use hh:mm:ss ?
Note: I did read the documentation and examples, and oddly enough there isn't anything about scheduling a job to run at exactly 7:45:30 PM. All the examples appeared to be geared towards cron jobs running every seconds=3.
Here is my code for schedule-module
import subprocess
import time
import schedule
def job1():
subprocess.call("netsh interface portproxy add v4tov4 listenaddress=192.168.0.153 listenport=1101 connectaddress=192.168.0.153 connectport=809 protocol=tcp", shell=True)
def job2():
subprocess.call("netsh interface portproxy reset", shell=True)
schedule.every().day.at("06:00").do(job1)
schedule.every().day.at("07:00").do(job2)

Related

2nd Function doesnt work until 1st function is completely executed in python

So basically, i have made a tkinter app that has a reminder utiliy in specific to generate notifications at the scheduled time. Everything works fine until I run the app module and another module having the notification generating function one at a time , but when I call the notification generating function intto the app module, my app doesnt work but the notification works. I want the app to run such that the notification generating function kind of runs in the background until the app module is open.
github link: https://github.com/click-boom/Trella
Looking into chatgpt i found terms like threading and multiprocessing, but i have no concept of that and still tried but didnt work.
Sure enough what you are looking for is multithreading.
Here is a simple example of how multithreading works (sorry for my lack of drawing skills).
This is how all monothread programs work. In most programming languages this is the default behaviour.
So in this example Second Task will have to wait for First Task to complete.
If you want several tasks to run concurrently, you can use multithreading.
This is how you could implement this in Python.
Monothreading:
from time import sleep
def firstTask():
time = 10
for i in range(time):
sleep(1)
print(f'I have been running for {i}s')
def secondTask():
print('All I want to do is run once')
firstTask()
secondTask()
Here, secondTask will only run after firstTask is done (i.e after 10 seconds).
Multithreading:
from threading import Thread
from time import sleep
def firstTask():
time = 10
for i in range(time):
sleep(1)
print(f'I have been running for {i}s')
def secondTask():
print('All I want to do is run once')
first_thread = Thread(target=firstTask)
second_thread = Thread(target=secondTask)
first_thread.start()
second_thread.start()
I hope this will be a help to someone !

Detecting change in website Python3

I am taking data from a webpage that updates every morning that updates at different times and I would like to know how to get a script to run every 10 minutes or so to check if the website has been updated. I was thinking of somehow using cron but I don't understand it very well. Thanks for your help.
Have you tried using the package APScheduler? It makes it fairly simple to schedule tasks. Here's the documentation.
To do a scheduled task, this is all that needs to be done (for something basic):
from apscheduler.schedulers.background import BackgroundScheduler
from pytz import utc
scheduler = BackgroundScheduler()
scheduler.configure(timezone=utc)
def print_hello():
print("Hello, this is a scheduled event!")
job = scheduler.add_job(print_hello, 'interval', minutes=1, max_instances=10)
scheduler.start()
Note, however, that I had a small bug when I first tried to use the library, but an explanation of how to fix that is here.

Is there any Python module available which can alarm after certain time

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

Writing a Python script that runs everyday till a specified date

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.

How can I schedule a Task to execute at a specific time using celery?

I've looked into PeriodicTask, but the examples only cover making it recur. I'm looking for something more like cron's ability to say "execute this task every Monday at 1 a.m."
Use
YourTask.apply_async(args=[some, args, here], eta=when)
And at the end of your task, reschedule it to the next time it should run.
The recently released version 1.0.3 supports this now, thanks to Patrick Altman!
Example:
from celery.task.schedules import crontab
from celery.decorators import periodic_task
#periodic_task(run_every=crontab(hour=7, minute=30, day_of_week="mon"))
def every_monday_morning():
print("This runs every Monday morning at 7:30a.m.")
See the changelog for more information:
http://celeryproject.org/docs/changelog.html
I have just submitted a patch to add a ScheduledTask to accomplish a small bit of time based scheduling versus period based:
https://github.com/celery/celery/commit/e8835f1052bb45a73f9404005c666f2d2b9a9228
While #asksol's answer still holds, the api has been updated. For celery 4.1.0, I have to import crontab and periodic_task as follows:
from celery.schedules import crontab
from celery.task import periodic_task
How you can read in this tutorial, you can make a PeriodicTask, i think if you have execute a task at 1 .am. Monday's morning is because you wan to run a long cpu/mem operation, rememeber celery use ampq for enqueue tasks.

Categories