Python: how to set a time to trigger a function? - python

How can I set a timer to run a function? right now I manually run the function. But what if I want to tell Python to run it in like 1 hour? how can I achieve this task?
Additionally, how about trying to run it at say 5pm today or tomorrow?
I tried the following but does not really work. What did I miss?
import datetime
from threading import timer
def hello_world():
print("hello world")
delta_t = datetime.time(0,1,0)
Timer(delta_t, hello_world)

import threading
def task():
print("hello world ")
timer = threading.Timer(5.0, task)
timer.start()

Related

Scheduling tasks in Python

import schedule
import time
def job(work):
print(work)
schedule.every().day.at("10:30").do(job(work))
while True:
schedule.run_pending()
time.sleep(1)
How to call job(work) inside my do() function. if i give job() it works fine, but if i give job(work) it throwing error. what to do with this? any help
This is in the schedule FAQ:
import schedule
import time
def job(work):
print(work)
schedule.every().day.at("10:30").do(job,work="") # make "" whatever string you want
while True:
schedule.run_pending()
time.sleep(1)

MultiThreading in AWS lambda using Python3

I am trying to implement Multithreading in AWS lambda. This is a Sample code that defines the format of my original code which I am trying to execute in lambda.
import threading
import time
def this_will_await(arg,arg2):
print("Hello User")
print(arg,arg2)
def this_should_start_then_wait():
print("This starts")
timer = threading.Timer(3.0, this_will_await,["b","a"])
timer.start()
print("This should execute")
this_should_start_then_wait()
In my local Machine, this code is working fine. The output I am receiving is:
This starts
This should execute
.
.
.
Hello User
('b', 'a')
Those 3 . represents that it waited for 3 seconds to complete the execution.
Now when I execute the same thing in AWS lambda. I am only receiving
This starts
This should execute
I think it's not calling the this_will_await() function.
Have you tried adding timer.join()? You'll need to join the Timer thread because otherwise the Lambda environment will kill off the thread when the parent thread finishes.
This code in a Lambda function:
import threading
import time
def this_will_await(arg,arg2):
print("Hello User")
print(arg,arg2)
def this_should_start_then_wait():
print("This starts")
timer = threading.Timer(3.0, this_will_await,["b","a"])
timer.start()
timer.join()
print("This should execute")
this_should_start_then_wait()
def lambda_handler(event, context):
return this_should_start_then_wait()
Produces this output:
This starts
Hello User
b a
This should execute

Run schedule function in new thread

I used the schedule library to schedule a function every X seconds:
Want I want is to run this function on separate thread. I found this in the documentation on how to Run the scheduler in a separate thread but I didn't understand what he did.
Is there someone who can explain to me how to do that ?
Update:
This what I tried:
def post_to_db_in_new_thread():
schedule.every(15).seconds.do(save_db)
t1 = threading.Thread(target=post_to_db_in_new_thread, args=[])
t1.start()
You don't really need to update schedule in every task
import threading
import time
import schedule
def run_threaded(job_func):
job_thread = threading.Thread(target=job_func)
job_thread.start()
schedule.every(15).seconds.do(run_threaded, save_db)
while 1:
schedule.run_pending()
time.sleep(1)

Python Threading Parameters Issue

I've been trying for around half an hour now and just cant seem to wrap my head around what im doing wrong here.
Working Code:
import threading
from time import sleep
def printX():
threading.Timer(5.0, printX).start()
print("five")
printX()
while True:
print("1")
sleep(1)
This works, however I need to be able to dynamically assign what the print statement will be along with the delay.
Desired Code:
import threading
from time import sleep
def printX(time, message):
threading.Timer(int(time), printX).start()
print(str(message)
printX(time, message)
while True:
print("Rest of the program continues")
sleep(1)
Thanks for any help in advance :).
threading.Timer could pass arguments with args:
threading.Timer(int(time), printX, (time, message)).start()
read more on its doc.
An alternative method is to define a class with printX as an inner function.
class thread:
def __init__(self, time, message):
self.time = time
self.message = message
def printX(self):
threading.Timer(int(self.time), self.printX).start()
print(str(self.message))
thread(3,"test message").printX()
while True:
print("Rest of the program continues")
sleep(1)

Python threading - How to repeatedly execute a function in a separate thread?

I have this code:
import threading
def printit():
print ("Hello, World!")
threading.Timer(1.0, printit).start()
threading.Timer(1.0, printit).start()
I am trying to have "Hello, World!" printed every second, however when I run the code nothing happens, the process is just kept alive.
I have read posts where exactly this code worked for people.
I am very confused by how hard it is to set a proper interval in python, since I'm used to JavaScript. I feel like I'm missing something.
Help is appreciated.
I don't see any issue with your current approach. It is working for me me in both Python 2.7 and 3.4.5.
import threading
def printit():
print ("Hello, World!")
# threading.Timer(1.0, printit).start()
# ^ why you need this? However it works with it too
threading.Timer(1.0, printit).start()
which prints:
Hello, World!
Hello, World!
But I'll suggest to start the thread as:
thread = threading.Timer(1.0, printit)
thread.start()
So that you can stop the thread using:
thread.cancel()
Without having the object to Timer class, you will have to shut your interpreter in order to stop the thread.
Alternate Approach:
Personally I prefer to write a timer thread by extending Thread class as:
from threading import Thread, Event
class MyThread(Thread):
def __init__(self, event):
Thread.__init__(self)
self.stopped = event
def run(self):
while not self.stopped.wait(0.5):
print("Thread is running..")
Then start thread with object of Event class as:
my_event = Event()
thread = MyThread(my_event)
thread.start()
You'll start seeing the below output in the screen:
Thread is running..
Thread is running..
Thread is running..
Thread is running..
To stop the thread, execute:
my_event.set()
This provides more flexibility in modifying the changes for the future.
What might be an issue is that you are creating a new thread each time you are running printit.
A better way may be just to create one thread that does whatever you want it to do and then you send an event to stop it when it is finished for some reason:
from threading import Thread,Event
from time import sleep
def threaded_function(evt):
while not evt.is_set():
print "running"
sleep(1)
if __name__ == "__main__":
e=Event()
thread = Thread(target = threaded_function, args = (e, ))
thread.start()
sleep(5)
e.set() # tells the thread to exit
thread.join()
print "thread finished...exiting"
I run it in python 3.6.It works ok as you expected .
I have used Python 3.6.0.
And I have used _thread and time package.
import time
import _thread as t
def a(nothing=0):
print('hi',nothing)
time.sleep(1)
t.start_new_thread(a,(nothing+1,))
t.start_new_thread(a,(1,))#first argument function name and second argument is tuple as a parameterlist.
o/p will be like
hi 1
hi 2
hi 3
....

Categories