Passing run_date in seconds to apscheduler's add_job - python-3.x

I want to schedule a function in APScheduler to happen only once in the specified time from now. The run_date date trigger accepts datetime objects and/or strings there of:
from datetime import datetime
import os
from apscheduler.schedulers.asyncio import AsyncIOScheduler
try:
import asyncio
except ImportError:
import trollius as asyncio
def tick():
print('Tick! The time is: %s' % datetime.now())
if __name__ == '__main__':
scheduler = AsyncIOScheduler()
scheduler.add_job(tick, 'date', run_date=datetime.fromordinal(datetime.toordinal(datetime.now())+1))
scheduler.start()
print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))
# Execution will block here until Ctrl+C (Ctrl+Break on Windows) is pressed.
try:
asyncio.get_event_loop().run_forever()
except (KeyboardInterrupt, SystemExit):
pass
Is there a built-in functionality in APScheduler to specify the delay time directly in seconds, e.g.something like application_start_time + specified_delay? I tried datetime.fromordinal(datetime.toordinal(datetime.now())+1) as argument to run_date for 1 second after the starting point of my application, but this only hangs for ever without calling the tick function showing the following deprecation message:
Press Ctrl+C to exit
/tmp/a.py:30: DeprecationWarning: There is no current event loop
asyncio.get_event_loop().run_forever()

What you probably wanted was:
from datetime import datetime, timedelta, timezone
scheduler.add_job(tick, "date", run_date=datetime.now(timezone.utc) + timedelta(seconds=1))

Related

How to control thread execution in Python3

Below python function executes after every 30 seconds, I would like to stop the thread execution after 1 hour (60 minutes) of total time. How can I get this ? Or polling is better than this ?
import time, threading
import datetime
def hold():
print(datetime.datetime.now())
threading.Timer(30, hold).start()
if __name__ == '__main__':
hold()
You could simply make use of the time module to do that in the following way
import time, threading
import datetime
def hold():
start = time.time()
while 1:
print(datetime.datetime.now())
# Sleep for 30 secs
time.sleep(30)
# Check if 1 hr over since the start of thread execution
end = time.time()
# Check if 1 hr passed
if(end - start >= 3600):
print(datetime.datetime.now())
break
if __name__ == '__main__':
# Initiating the thread
thread1 = threading.Thread(target=hold)
thread1.start()
thread1.join()
print("Thread execution complete")

The python program with datetime mofule

I write this code in python in order to read the minute of windows clock and recognize weather it is even or odd and do it 10 times with random sleep time between 5 to 10 seconds:
from datetime import datetime
import random
import time
wait_time = random.randint(5,11)
time.sleep(wait_time)
for i in range(10):
even=[2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,
34,36,38,40,42,44,46,48,50,52,54,56,58]
m=datetime.today().minute
if m in even:
print("It is even")
else:
print("It is odd")
But when I run it, sleep time works ok but it show the answer just one time. I think I should write the lines in other arrangement. But I don't know how to fix it.
You need to rearrange your lines according to your own description as below. Same lines but another ordering.
from datetime import datetime
import random
import time
even=[2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,
34,36,38,40,42,44,46,48,50,52,54,56,58]
for i in range(10):
m=datetime.today().minute
if m in even:
print("It is even")
else:
print("It is odd")
wait_time = random.randint(5,11)
time.sleep(wait_time)

apscheduler calling function params only once

I have tweaked this basic example to illustrate the point in the subject:
https://github.com/agronholm/apscheduler/blob/master/examples/executors/processpool.py
Here is the tweaked code(see args=[datetime.now()])
#!/usr/bin/env python
from datetime import datetime
import os
from apscheduler.schedulers.blocking import BlockingScheduler
def tick(param):
print('Tick! The time is: %s' % param)
if __name__ == '__main__':
scheduler = BlockingScheduler()
scheduler.add_executor('processpool')
scheduler.add_job(tick, 'interval', seconds=3, args=[datetime.now()])
print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))
try:
scheduler.start()
except (KeyboardInterrupt, SystemExit):
pass
When I run it, the output timestamp does not update:
$ ./test.py
Press Ctrl+C to exit
Tick! The time is: 2019-01-28 19:41:53.131599
Tick! The time is: 2019-01-28 19:41:53.131599
Tick! The time is: 2019-01-28 19:41:53.131599
Is this the expected behavior? I'm using Python 3.6.7 and apscheduler 3.5.3, thanks.
This has nothing to do with APScheduler. What you're doing could be rewritten like this:
args = [datetime.now()]
scheduler.add_job(tick, 'interval', seconds=3, args=args)
You're calling datetime.now() and then passing its return value in a list to scheduler.add_job(). Since you're passing a datetime, how do you expect APScheduler to call datetime.now() every time the target function is executed?

Python 3 BlockingScheduler killed without apparent reason

I am running a basic blocking scheduler and it is being killed without apparent reason. In my console, a "Killed" message appears but that's all. Any idea how I could obtain a reason as to why it was killed? My function is as simple as the one below.
from apscheduler.schedulers.blocking import BlockingScheduler
import pandas as pd
import time
sched = BlockingScheduler()
#sched.scheduled_job('cron', day_of_week='mon,tue', hour=17, minute=45)
def scheduled_job():
print("Start time: ", pd.datetime.now(), "\n")
fct.start()
time.sleep(100)
fct.stop()
print("End time: ", pd.datetime.now(), "\n\n")
return
sched.start()

TypeError: the first argument must be callable

I'm using a chron job like using schedule.
This is my code
import schedule
import time
def rank():
import new_user as nu
nu.new_user()
print('successfully loaded')
return
schedule.every(5).minutes.do(rank())
while 1:
schedule.run_pending()
time.sleep(1)
whenever I run this code I'm getting an error message as follows:
TypeError: the first argument must be callable
replace rank() with rank in do method invocation
import schedule
import time
def rank():
import new_user as nu
nu.new_user()
print('successfully loaded')
return
schedule.every(5).minutes.do(rank)
while 1:
schedule.run_pending()
time.sleep(1)

Resources