How can i refresh the current date inside a running Python process? - python

I'm using supervisord to keep a Telegram bot developed with Python running on a server and I'm using the datetime library to get the current date and perform an operation that depends on the current date.
from datetime import date
today = date.today()
The problem: I noticed that, when the process is running, the Python always returns the same date; so, my bot doesn't return a different output each day, but the same.
To solve that, I had to enter the server, stop supervisor, kill the process and, manually, execute the python script to run the bot with the current date.
I thought about using a crontab to run supervisorctl restart all one time per day, but when i run that command the Python process doesn't stopped, even when I killed the process and run that command the output still returned the date of yesterday, I needed to manually run python3 myfile.py to refresh it. There is a way that I can actualize the Python date.today() without killing the process, or a way that I can kill and restart the Python process refreshing the current date?
The current code:
def get_today_meditation(update, context):
chat_id = update.message.chat_id
today = date.today()
print(today)
[ ... ]
def main():
key_api = os.environ.get('PYTHON_API_BREVIARIO_KEY')
locale.setlocale(locale.LC_ALL, "pt_BR.UTF-8")
updater = Updater(key_api, use_context=True)
dispatcher = updater.dispatcher
dispatcher.add_handler(CommandHandler('meditacaodehoje', get_today_meditation))
updater.start_polling()
updater.idle()

Related

Python Schedule - Execute at the time of server starting

I need to execute a task.
i want to delete a table details at the interval of 30 days.
and i want to execute the task automatically while our server starts(after executing python manage.py runserver)
then i tried
pip install schedule
my scheduler function
def set_timeschedule():
HeartBeatLog.objects.all().delete()
then i dont understand i call the function
so i called this in urls.py
if date.today().day == 28:
schedule.every().day.at("16:36").do(set_timeschedule)
time added for testing ( i need to execute them in 30 days gap)
here HeartBeatLog is my modal. and i cant get this in manage.py or urls.py
but its not working
Is this is the Proper way for doing task ?
How can i get the Exact data.
where i put this code to delete the data while staring the server.
is it possible to kill the schedule after 1 time execution
You can set it up as such:
def set_timeschedule():
if date.today().day == 28:
HeartBeatLog.objects.all().delete()
schedule.every().day.at("16:36").do(set_timeschedule) # Sets up a job
while True:
schedule.run_pending() # Checks for active jobs and runs
sleep(900) # Sleep for 900s
You need to have run_pending() for the jobs that are scheduled to run

Schedule to run .exe file created using pyinstaller at specific time and day.(not task scheduler)

I have worked on a python project and have created a .exe file using pyinstaller. Now i have the executable file which i need to run on each and every machine (desktop/laptop) in my company. i am looking for a scheduling solution, where i can schedule the .exe file to run after every 2 hours and only on specific days.
Can some one guide me to a scheduling tool or any way where i can schedule to run the executable file on every machine.
things to consider : A solution which don't need or say less software to be installed in all the machines. The reason i created .exe file using pyinstaller is it doesn't need python to be installed in all the machines.
I would do something like the code reported above.
Note that here in the exemple I have set a sleep of one second, this means that every second the function checks if it is the right time to execute the job.
If your execution time precision is in minutes you can have a sleep of 60''.
import time
# here the time and date when you want to execute your job
datetime_of_exe = 'Mon Dec 14 12:00:00 2020'
# this is the job I want to do
def job():
print('I am working now!')
# this function to check if it is the right datetime to execute the job
def timeToExecute(datetime):
if time.ctime() == datetime:
return True
else:
return False
# this loop works 24h and exits after the job is done
while True:
if timeToExecute(datetime_of_exe):
job()
exit()
time.sleep(1)

Apscheduler script file stops silently - no error

I have a scheduler_project.py script file.
code:
from apscheduler.schedulers.background import BackgroundScheduler
scheduler = BackgroundScheduler()
def func_1():
# updating file-1
def func_2():
# updating file-2
scheduler.add_job(func_1, 'cron', hour='10-23' , minute='0-58', second=20)
scheduler.add_job(func_2, 'cron', hour='1')
scheduler.start()
When I run, (on Windows machine)
E:\> python scheduler_project.py
E:\> # there is no error
In Log: (I have added logging in above code at debug level)
It says, job is added and starts in (some x seconds), but it is not
starting.
In task manager, the command prompt process display for a second and disappear.
And my files are also not getting updated, which is obvious.
What's happening? What is the right way to execute this scheduler script?
Scheduler was created to run with other code - so after starting scheduler you can run other code.
If you don't have any other job then you have to use some loop to run it all time.
In documentation you can see link to examples on GitHub and one of example uses
while True:
time.sleep(2)

Is it better to schedule a python script via Task Scheduler or with code to run when needed?

So this is something I have been wondering for a while, and while I don't know if there is a correct answer there is probably a better option.
So which of the options below is best to schedule a python script to run at a specific time? Let me know what you prefer, or if you have an alternative.
1) Take a python file script.py, write a ".bat" file to run the code in command prompt, and then use windows native task scheduler to launch the file at a specific time each day.
BAT Example:
cd C:\Users\Administrator\Documents\Scripts
python script.py
This is some code for a BAT file that will run your python script.
2) Use python to create a timed task within your file like some of the examples below:
import schedule
import time
def job():
print("I'm working...")
schedule.every(10).minutes.do(job)
schedule.every().hour.do(job)
schedule.every().day.at("10:30").do(job)
while 1:
schedule.run_pending()
time.sleep(1)
or
from datetime import datetime
from threading import Timer
x=datetime.today()
y=x.replace(day=x.day+1, hour=1, minute=0, second=0, microsecond=0)
delta_t=y-x
secs=delta_t.seconds+1
def hello_world():
print "hello world"
#...
t = Timer(secs, hello_world)
t.start()
or
from datetime import date
from apscheduler.scheduler import Scheduler
# Start the scheduler
sched = Scheduler()
sched.start()
# Define the function that is to be executed
def my_job(text):
print text
# The job will be executed on November 6th, 2009
exec_date = date(2009, 11, 6)
# Store the job in a variable in case we want to cancel it
job = sched.add_date_job(my_job, exec_date, ['text'])
# The job will be executed on November 6th, 2009 at 16:30:05
job = sched.add_date_job(my_job, datetime(2009, 11, 6, 16, 30, 5), ['text'])
When it comes to option 2 there are plenty of examples I could include but I just want to know whats better in your opinion.
Does one of the options use more processing power? Is one of the options more reliable? etc.
I will choose option 1. If you choose option 2, your code will not run in several circumstances, such as your machine restart or your python IDE crashes.
Option 1 will run your code as long as your machine is running.
I have never used Option 2 personally.
In general, if you just have one or two servers. Task Scheduler (Windows) or cron (Linux) would be the way to go.
There are also tools like AutoSys that are built for scheduling batch jobs.

APScheduler not executing the python

I am learning Python and was tinkering with Advanced scheduler. I am not able to gt it working though.
import time
from datetime import datetime
from apscheduler.scheduler import Scheduler
sched = Scheduler(standalone=True)
sched.start()
##sched.cron_schedule(second=5)
def s():
print "hi"
sched.add_interval_job(s, seconds=10)
i=0
while True:
print i
i=i+1
time.sleep(3)
sched.shutdown()
I am sure I am missing something basic. Could someone please point it out?
Also would you recommend a crontab to the advanced scheduler? I want my script to run every 24 hours.
Thanks
Standalone mode means that sched.start() will block, so the code below it will NOT be executed. So first create the scheduler, then add the interval job and finally start the scheduler.
As for the crontab, how about just sched.add_cron_job(s, hour=0)? That will execute it at midnight every day.

Categories

Resources