Python Wait /Pause until specific Time... And stop at end of schedule - python-3.x

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)

Related

Python loop issue for Binance API

Hi i have 2 python files and first file for data and its working with timer, example first file timer is set for 02/05/2023 - 02:50am and when this date is come this file triggered and opens the order, but 2st file is checks this order status i mean 2st file is only for checks status and if this order succes its print 'SUCCES' and if its not its print 'FAIL'
but it need to open like 2-3 days but its fail and says:
raise ConnectionError(err, request=request)
requests.exceptions.ConnectionError: ('Connection aborted.', error(54, 'Connection reset by peer'))
i dont want to solve binance problem bec its nearly impossible, i found solution for this i write this command in terminal every time:
while true; do python3 /home/pi/Desktop/EREN/2-SHORTnormal/Loop.py && break; done
'This command help me for if its crash for anything like timestamp, time out or anything its start again '
but every time :(
Im waiting the trigger date (example 02/05/2023-02:50am) and i dont want to wake up for
open termnial write this command bla bla
WHAT I WANT:
I only want these files in one file like when i start the program its wait for trigger date and when its trigger i want it to start other file and if its crash i want to restart this program automatically but not to entire command, only the second one because if its start entire code its wait for trigger again but its cant trigger bec the trigger date it will already be past. How i can do this in python
example if this is my code:
Print('order is sent') #this is first files command and this work good
#and then
while status == succes
Print('order status:',status) #this is second files command
But second part crashes sometimes and i want to re open when it crashes until its status == success but only second part not whole code.
Okey i think i found the solution:
import time
#my 1.Command out the while loop,
while True:
try:
#my 2.Command
continue
except:
print("Program has crashed and restarts in 2 sec.")
time.sleep(2)
continue
if 2.Command is crash its print something and restart program. And 1.Command is run for only 1 time this is what i. want

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.

Timer that runs in the background in Python 3.7.0

I am trying to make a timer in my text-based adventure games so that for every second that passes, 1 hp is taken away from the user, while they are in a certain scenario and can still use other functions. Here's my code:
#Imports and base variables
import time
import threading
import random
hp=100 #Health
p="snow" #Starting point
invtry=[] #Inventory of Character
#Function to drop health
def hlthdrp():
hp-1
t=threading.Timer(1.0,hlthdrp)
t.start()
while p=="snow" or p=="Snow":
if hp==0 and p=="snow" or p=="Snow":
print ("You died of frostbite")
t.cancel()
threading.wait(timeout=5.0)
As of right now, I'm not getting any errors, but instead, a completely blank shell, or terminal. If anyone could help, that'd be great!
You must call threading.Timer recursively else it only calling one time
And you can use lower() function to compare snow or some string
There is your fixed code i hope it will be usefull for you.
def hlthdrp():
global hp
print(hp)# just for testing
hp=hp-1
if hp!=0:
threading.Timer(1, hlthdrp).start()
hlthdrp()
while p.lower()=="snow":
if hp==0 :
print ("You died of frostbite")
elif hp!=0 :
pass

Sub program auto send results to main program (for LineBot on Heroku)

Well~ briefly decribe
I'm working on LineBot which set on Heroku
Main program is already done
And now working on it's function which may need sub program
1.
My sub program use timer which runs every 20 seconds
Mainly use to detect newest earthquake info publish by government
and send to every user directly
I hope it can automatically send some result(time infomation) to my Main program in every 20 seconds (that's why I use Timer)
Is it possible?
(I can't use timer in Main program once I run other function Timer may stop...)
2.If it's possible how do I set or use my Sub program on Heroku?? (or maybe on other site which can help it auto run and send result to my Main program)
3.Can anyone teach me(or give me links) how to link two program together
ex:
A.py as Main
B.py as Sub
What should I do on B.py (ex: the form of it's result) so I can return results to A.py
Thanks a lot !!!
sub program code
from datetime import datetime
from threading import Timer
def printTime(inc):
dt = datetime.now()
m=dt.strftime('%m')
d=dt.strftime('%d')
H=dt.strftime('%H')
M=dt.strftime('%M')
print(m+d+H+M)
t = Timer(inc, printTime, (inc,))
t.start()
printTime(20)

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