python schedule to run another file.py every certain time - python-3.x

I have a python script in file called tasks.py containing multiple tasks, processes and functions (and it works perfect to me).
i want to run this file (tasks.py) at certain time ( 1:00 am & 4:45 am & 11:35 am & 6:25 pm & 9:10 pm) every day starting from date say as example 6 aug 2018.
so i created a new file and called it run.py
i used the following code to import tasks.py file
#!/usr/bin/python
import tasks
but i want to schedule this import in the certain times as mentioned above starting from the required date
i tried while function, schedule module, cron module and import os but i failed with all
any body can help please ????

The simple solution can be something like that
import datetime
from time import sleep
rest_seconds = 3600 # sleep for one hour, so the task won't be called few times per hour
while True:
if datetime.datetime.now().hour == 12:
do_task()
sleep(rest_seconds)
If you need a complex one, I use Airflow framework for building scheduled tasks/pipelines

Related

Python Defining Business days and working hours

I am looking for guidance on how to create a variable (Business_Time) which contains only business days (not weekends) and where i can set working hours (9am - 6pm GMT).
The reason for this is because i'm trying to calculate some SLA's (how long employees have to complete a task), however if the end time falls outside of these business days/hours, then i can set it to a specific time.
Many thanks
pandas already implement BusinessHour and BusinessDay:
from pandas.tseries.offsets import BusinessDay
from pandas.tseries.offsets import BusinessHour
from dateutil import parser
myDate = parser.parse('Fri, 7 Jan 2022 17:00:00 +0000 (UTC)')
myWorkTime = BusinessDay(1) + BusinessHour(1)
print(myDate + myWorkTime)
This will print Timestamp('2022-01-11 10:00:00+0000', tz='tzutc()').
You can find a lot of tutorials over the internet (like this one for example)

Python Wait /Pause until specific Time... And stop at end of schedule

With the following code, I am trying to run program between 9:15am and 17:30pm;; and it should esentially stop at 17:30pm and then, again wait until next day 9:15am without ending itself.
### For experiment sake, I have made the datetime.time(20,26) and (20,28)...
### You may change it to any of the hours and mins of your time...
### But I am hoping it would start and stop between those times please...
import time, datetime, pause
def printing_something():
print("Hello World") # you can add any func here
day_of_week = datetime.date.today().weekday() # (0=Monday), (5=Saturday) and (6=Sunday)
timer_now = datetime.datetime.now().time()
while True:
if day_of_week < 5 and (timer_now > datetime.time(20,26) and timer_now < datetime.time(20,28)):
time.sleep(5 - time.time() % 5)
printing_something()
else:
pause.until(datetime(9, 15, 0))
Firstly...
The problem with this code is it doesn't do anything at the start of the time, in case I start like an hour before the schedule... It shows it is running, but when the exact time comes(for example 20:26hours, like in code above), it just doesn't print anything that it is asked.
Secondly...
If I happen to start inside the scheduled time, then it will start printing, but then it doesn't stop the printing at the end of 20:28hours, like it is scheduled to stop...
So, the question again...
If I start the program anytime in day or night, and leave it... How to make it execute at 9:15am and make it stop at 17:30pm... and then allow the program to keep running(but paused) until the next day 9:15am....
(For more clarity, I was trying to run in the market hours only, between Monday to Friday... and parts of the code may not be relevant, but I am a rookie in python, sorry)
As there has not been much help from here, I have worked out a temporary work-around with the below code. I manually start the program execution at the start of the day, and then at 17:30pm, I close the program.
import schedule
import time
def job():
print("I'm working...")
schedule.every(5).minutes.do(job)
schedule.every().day.at("9:15").do(job)
while True:
schedule.run_pending()
time.sleep(1)

Print time in terminal, and update time every 30 seconds

I am writing a discord bot using discord.py and python 3.7. I have a loop that changes the bot's activity, prints out the current time in the terminal and current ping in the terminal every 30 seconds. But the problem is that it's not printing the updated time. If I start the bot at 15:23:52, the bot will always print 15:23:52, for the next hours. It doesn't update its time.
import discord, datetime, time
import datetime as DT
time_date_now = DT.datetime.now().strftime('Date: %d-%m-%Y\nTime: %H:%M:%S')
*****
#tasks.loop(seconds=30)
async def change_status():
await client.change_presence(activity=discord.Game(f'Ping: {round(client.latency * 1000)}ms'))
print(time_date_now)
print(f'Ping: {round(client.latency * 1000)}ms\n---------------------------')
How can I update the printed time correctly?
The variable time_date_now is declared and assigned only once at the start of your script. If you move that inside your task, you'll see it working.

Get Current Day w.r.t timezone [duplicate]

This question already has answers here:
Display the time in a different time zone
(12 answers)
Python get current time in right timezone [duplicate]
(1 answer)
Closed 3 years ago.
The following code snippet print the day for example. Monday (or) Tuesday etc..
But on my local machine its printing as per Indian Standard time Timezone but on my server, its printing as per UTC.
import datetime
from datetime import date
current_day_name = (date.today().strftime("%A")).lower()
print(current_day_name)
Can someone please suggest how do i tweak this code as per a specific timezone like Indian Standard Time (or) UTC?
Here is a quote from the datetime library reference:
Because the format depends on the current locale, care should be taken when making assumptions about the output value.
So datetime depends on the locale settings. The locale reference describes a function setlocale:
Applications typically start with a call of:
import locale
locale.setlocale(locale.LC_ALL, '')
So, first make sure you have whichever language-pack you need (e.g. sudo apt install language-pack-id) then specify the locale as described in the documentation.
As an example, on my computer I run
>>>import locale
>>>locale.getdefaultlocale()
('en_US', 'UTF-8')
>>>datetime.date.today().strftime('%A')
'Saturday'
>>> locale.setlocale(locale.LC_ALL,'hr_HR.utf8')
'hr_HR.utf8'
>>> datetime.date.today().strftime('%A')
'subota'
It looks like you might also need to supply tzinfo to your datetime constructor (see the datetime reference). For example:
>>> datetime.datetime.now(datetime.timezone.utc).strftime('%c, %Z,%z')
'Sat 15 Feb 2020 01:07:16 PM , UTC,+0000'
>>> datetime.datetime.now(datetime.timezone(
datetime.timedelta(hours=1),'CET')).strftime('%c, %Z,%z')
'Sat 15 Feb 2020 02:07:28 PM , CET,+0100'

Python script stops to execute on startup after some time

More than a month ago I've added this script to my startup applications. It worked just like it should, every single time.
Now, for some reason, it's not working every single time (primarily it's not working every single time in the morning, there are different variations now).
I've changed the interpreter, shortened paths - it didn't help. And when nothing happens, after (and before) typing a command to find all working python processes
ps -fA | grep python
this process is there.
I'm on Linux Mint 18.3 MATE. Thanks.
#! /usr/bin/python3
"""My Alarms."""
import schedule
import time
import webbrowser
import subprocess
def breakfast():
"""Breakfast reminder."""
subprocess.Popen(['notify-send', 'TIME TO EAT BREAKFAST'])
webbrowser.open('/path_to/carbon.ogg')
def dinner():
"""Dinner reminder."""
subprocess.Popen(['notify-send', 'TIME TO MAKE A DINNER'])
webbrowser.open('/path_to/carbon.ogg')
def shut_down():
"""Shut Down (Laptop) reminder."""
subprocess.Popen(['notify-send', 'TIME TO SHUT DOWN THE PC'])
webbrowser.open('/path_to/carbon.ogg')
schedule.every().day.at("07:35").do(breakfast)
schedule.every().day.at("17:10").do(dinner)
schedule.every().day.at("21:00").do(shut_down)
while True:
schedule.run_pending()
time.sleep(1)
Turns out, I haven't met requirements for the schedule module. Some of these modules were updated, some were missing. Now it's working like it used to be. Case closed.

Resources