Exectue function every one hour in Python - python-2.7

I wanted to execute a program every once hour. I can use time.sleep function to delay the interval but, if the program executed let's say at 16:30 then the function will only execute at 17:30. But I need to execute the function at 17:00, 18:00 and so on.
import datetime
def onehour(value):
print "%d Hours" % value
now = datetime.datetime.now()
oncehour(now.hour)

You need to sleep first, if current time is 12:23, then you need to sleep 60-23 = 37 minutes and then run your code every hour.
Here you can write like this:
import time
import datetime
time.sleep(60 * (60 - datetime.datetime.now().minute))
while True:
do_smth()
sleep(60 * 60)

What about Cron jobs ? You can write your code inside a Python file then call it from command line inside your crontab:
0 * * * * python script.py

Related

How to run an Airflow DAG once after x minutes?

I need to run a DAG exactly once, but waiting 10 minutes before:
with models.DAG(
'bq_executor',
schedule_interval = '#once',
start_date= datetime().now() + timedelta(minutes=10) ,
catchup = False,
default_args=default_dag_args) as dag:
// DAG operator here
but I can't see the execution after 10 minutes. Something wrong with start_date?
If I use schedule_interval = '*/10 * * * *' and start_date= datetime(2019, 8, 1) (old date from now), I can see the excution every 10 minutes
Dont use datetime.now() as it will keep on changing whenever the DAG is loaded and now() + 10 minutes will always be a future timestamp resulting in DAG never getting scheduled.
Airflow runs the DAGS you have added always AFTER the start_date. So if you have start_date today, it will start after today 23:59.
Scheduling is tricky for this, so check the documentation and examples:
https://airflow.apache.org/scheduler.html
In you case, just switch the start_date to yesterday (or today -1) and it will start today with yesterday's ds (date stamp)

How do I run my python application daily three times

I have a python application which creates JSON files. I need to execute an application three times per day at midnight, noon and evening.
import json
def add():
a = 10
b = 20
c = a+b
f = open("add.json","w")
f.write(str(c))
def subtract():
a = 10
b = 20
c = b-a
f = open("subtract.json","w")
f.write(str(c))
add()
subtract()
I need to run the application at a specified time automatically
You have 2 possibilities :
1- Let your code run with some timer !
For windows user:
2- use the AT command to create 3 scheduled tasks!
For Linux user:
2- use the Cron command to create 3 scheduled tasks !
which seems to be the best solution in your case!

How To Use The Current Local Time of Day To Control A Process Without Dates

I need to stop a process at 8:00 PM PDT everyday or as soon as possible after 8:00 PM. I see a lot about other uses of the time function but the examples all seem to be a difference in time, the timing of something, or always have the date included.
Could someone please provide an example along the lines of how I make something like this work...?
if currenttime >= 8:00 PM PDT:
time.sleep(99999999)
And also, what will I need to import, and how do I do the import?
the method I know is:
import datetime #this is the way to import a module named datetime...
import time #this module is used to sleep
a = str(datetime.datetime.now()) #a = '2016-03-27 00:20:28.107000' #for example
a = a.split(' ')[1] #get rid of the date and keep only the '00:20:28.107000' part
if a.startwith('20:00'): time.sleep(3600*12) #sleep for 12 hours (43200 seconds)
hope this helps you
edit: change timezone to pdt:
import datetime,pytz #for python_TimeZone
a = str(datetime.datetime.now(pytz.timezone('US/Pacific'))) #basically get the time in the specified zone
#from here continue as above...
taken from: http://www.saltycrane.com/blog/2009/05/converting-time-zones-datetime-objects-python/
good luck (next time try searching it in google...)
I actually ended up using a combination of hai tederry's answer and that found on http://www.saltycrane.com/blog/2008/06/how-to-get-current-date-and-time-in/
resulting in:
import time # import time library
import datetime # this is the way to import a module named datetime...
import pytz # imports Python time zone (needed to first do: sudo easy_install --pytz upgrade)
now = datetime.datetime.now(pytz.timezone('US/Pacific'))
timenow = now.strftime("%I:%M %p")
print timenow
if timenow > "08:30 PM" and timenow < "08:45 PM":
print "Programmed Pause"
time.sleep(999999)
This creates a time only output in your local 12 hour format with AM/PM that can be used in if statements, etc.

Python make script run at specified time daily

I want to make this script to run automatically once or twice a day at a specified time, what would be the best way to approach this.
def get_data():
"""Reads the currency rates from cinkciarz.pl and prints out, stores the pln/usd
rate in a variable myRate"""
sock = urllib.urlopen("https://cinkciarz.pl/kantor/kursy-walut-cinkciarz-pl/usd")
htmlSource = sock.read()
sock.close()
currancyRate = re.findall(r'<td class="cur_down">(.*?)</td>',str(htmlSource))
for eachTd in currancyRate:
print(eachTd)
print currancyRate[0]
myRate = currancyRate[0]
print myRate
return myRate
You can use crontab to run any script at regular intervals. See https://stackoverflow.com/a/8727991/1517864
To run a script once a day (at 12:00) you will need an entry like this in your crontab
0 12 * * * python /path/to/script.py
You can add a bash function.
while true; do <your_command>; sleep <interval_in_seconds>; done

cron job is running two times instead of one in a particular time?

I am trying to implement cron job in flask. Code structure is like
this:
code:
#sched.cron_schedule(second='*/30')
def some_decorated_task():
time_now = datetime.datetime.now()
print time_now
print "##########0######"
output:
2015-03-01 23:53:30.001843
##########0######
2015-03-01 23:53:30.002615
##########0######
Why it printing two time instead of one ?