Timer to perform task in Python --CLOSED-- - python

I know this question is not that good but I am kind of stuck here and I've been searching about timers but the answers are just not what I am looking for.
Okay so I have a for loop here and this for loop is trying to do something continuously but I need it to do its task for a minute that I have chosen and let's say 3 minutes , so it would be like
for i in sample_iteration:
#Tasks are being done here
But I need those tasks inside the for loop to keep going for 3 minutes and I have found this timer from geeks for geeks and this is the code
# import the time module
import time
# define the countdown func.
def countdown(t):
while t:
mins, secs = divmod(t, 60)
timer = '{:02d}:{:02d}'.format(mins, secs)
print(timer, end="\r")
time.sleep(1)
t -= 1
print('Fire in the hole!!')
# input time in seconds
t = input("Enter the time in seconds: ")
# function call
countdown(int(t))
Now I tried this one right here, now it does the countdown for 3 minutes but it also does the time.sleep(1) for one second and I can't have it paused for every second cause I need to to keep going as possible.
t = 180 #seconds
for i in sample_iteration:
mins, secs = divmod(t, 60)
timer = '{:02d}:{:02d}'.format(mins, secs)
print(timer, end="\r")
time.sleep(1)
t -= 1
#Do the task here
I can easily I think make a condition that when t is 0 I could break the loop
Now long ago I had this java program that does the work and involves some nano time with I understand this and the counting is based on nano time cause 100000000 nanoseconds is equal to 1 second right? (correct me if I am wrong) so yeah and here is the code
public class Timer {
public static void main(String[] args){
long lastTime = System.nanoTime();
boolean running = true;
int timer = 0;
long now ;
int i = 0;
while(running)
{
now = System.nanoTime();
timer += (now - lastTime);
lastTime = now;
if(timer >= 1000000000)
{
i++;
timer = 0;
System.out.println(i);
}
}
}
}
I was thinking of doing the same with python but I'm getting lost to be honest and I am just a beginner and tried to get help here in this great community! Also maybe there's an alternative where I do not have to apply based on the java program cause maybe there's a better way and shorter way with python. Thank you! Looking forward for this THANK YOU!

import time
def countdown(t):
start_time = time.time()
while True:
if int(time.time()-start_time) == t:
quit()
try this.

---UPDATE---
Hello I managed to figure it out! Thanks for the answers this is what I've done
i = 0
lastTime = time.time_ns()
timer = 0
for i in sample_iteration:
now = time.time_ns()
timer += (now - lastTime)
lastTime = now
if timer >= 1000000000:
i+=1
timer = 0
print(i)
I used the time.time_ns() to get the nanoseconds cause time.time() is different vs time.time_ns(). time.time() is getting the time in seconds since the epoch and it is not in nano seconds which is what I was looking for
time.time_ns() method of Time module is used to get the time in nanoseconds since the epoch. To get the time in seconds since the epoch, we can use time.time() method.
The epoch is the point where the time starts and is platform dependent. On Windows and most Unix systems, the epoch is January 1, 1970, 00:00:00 (UTC) and leap seconds are not counted towards the time in seconds since the epoch. To check what the epoch is on a given platform we can use time.gmtime(0).
Source: Geeks for Geeks
Thank you stack overflow community!

Related

How can I write a loop to make the timer run every two seconds

I have a question on how I am able to set the timer so that every time it exits the loop it sets the time back to 2 seconds. The problem is that the first time the sound works after 2 seconds, the next times it is executed immediately. Thank you very much in advance for any advice.
This is my code:
time = 2
while time > 0:
timer = datetime.timedelta(seconds=time)
time -= 1
duration = 1000
freq = 440
winsound.Beep(freq, duration)
I am not sure if you meant that, but for me it seems like you just want to wait 2 seconds before executing the next steps. You can do that like so:
import time
while True:
time.sleep(2) # waits 2 seconds
winsound.Beep(440, 1000)
Anyways I don't recommend you to use a plain infinite loop, without a break statement. Therefore I recommend you to add one, like down below.
import time
while True:
time.sleep(2) # waits 2 seconds
winsound.Beep(440, 1000)
if True: # break on a specific statment
break
Edit: As CrazyChucky mentioned in the comments, this approach should work fine in most of the cases, but it can end up being more than two seconds sometimes. Therefore you should work with timedeltas or take a look at scheduler.
To be more accurate as possible use:
import time
timer = 0
step = 2
t0 = time.time()
while True:
timer = time.time() - t0
wait = step - timer
time.sleep(wait)
print(time.time())
winsound.Beep(freq, duration)
t0 = time.time()
This script take in count the execution time of script lines for your computer.
You just have to reinitialize the time at the end of the loop
time = 2
while True:
timer = datetime.timedelta(seconds=time)
time -= 1
duration = 1000
freq = 440
if time == 0:
time = 2
break
winsound.Beep(freq, duration)

How to sleep python script for xx minutes after every hour execution?

I am trying to make a python script that works in a loop mode with iteration through a text file to run for periods of one hour and make 30minute pauses between each hour loop .
After some searching I found this piece of code :
import datetime
import time
delta_hour = 0
while:
now_hour = datetime.datetime.now().hour
if delta_hour != now_hour:
# run your code
delta_hour = now_hour
time.sleep(1800) # 1800 seconds sleep
# add some way to exit the infinite loop
This code has a few issues though :
It does not consider one hour periods since the script starts running
It does not seem to work continuously for periods over one hour
Considering what I am trying to achieve (running script 1hour before each time it pauses for 30mins) what is the best approach to this ? Cron is not an option here .
For clarification :
1hour run -- 30min pause -- repeat
Thanks
Here is a so simple code, I have written for teaching purposes, which is very clear
from datetime import datetime
class control_process():
def __init__(self, woking_period, sleeping_period):
self.woking_period = woking_period # working period in minutes
self.sleeping_period = sleeping_period # sleeping period in minutes
self.reset()
def reset(self):
self.start_time = datetime.utcnow() # set starting point
def manage(self):
m = (datetime.utcnow() - self.start_time).seconds / 60 # how long since starting point
if m >= self.woking_period: # if exceeded the working period
time.sleep(self.sleeping_period * 60) # time to sleep in seconds
self.reset() # then reset time again
return # go to continue working
cp = control_process(60, 30) # release for 60 minutes and sleep for 30 minutes
while True: # you code loop
cp.manage()
'''
your code
'''
in which 'control_processobject - I calledcp- callscp.manage()` inside your executing loop.
you reset time via cp.reset() before going in the loop or whenever you want
Based on Comments
The simplicity I mean is to add this class to your general library so you can use it whenever you want by instantiation of cp then one or two controlling functions 'cp.manage()` which control the working cycles, and cp.reset() if you want to use it in another location of the code. I believe that use a function is better than a long condition statement.
Using the default library you could do something like call the script itself using subprocess. By checking whether conditions are met the process could do a task and call itself. Extending the logic with a kill pill would make it stop (I leave that up to you).
import argparse, time
from subprocess import call
DELAY = 60 * 30 # minutes
WORK_TIME = 60 * 60 # minutes
parser = argparse.ArgumentParser()
parser.add_argument("-s",
help = "interval start time",
type = float,
default = time.time())
parser.add_argument("-t",
help = "interval stop time",
type = float,
default = time.time() + WORK_TIME)
def do_task():
# implement task
print("working..")
return
if __name__ == "__main__":
args = parser.parse_args()
start = args.s
stop = args.t
# work
if start < time.time() < stop:
do_task()
# shift target
else:
start = time.time() + DELAY
stop = start + WORK_TIME
call(f"python test.py -t {stop} -s {start}".split())
The simplest solution I could come up with was the following piece of code, which I added inside my main thread :
start_time = int(time())
... #main thread code
#main thread code end
if int(time() - start_time >= 60 * 60):
print("pausing time")
sleep(30 * 60)
start_time = int(time())
From the moment the script starts this will pause every hour for 30mins and resume afterwards .
Simple yet effective !

How to restart current seconds to 59 and start counting down

I'm trying to make a break timer. I can get the current second value, but I don't know how to reset the seconds and start counting down
I've tried several formulas found here on stack overflow, but have yet to find what I'm looking for
import time
while True:
now = time.localtime(time.time())
print(now[5])
time.sleep(1)
I expect the output to count down from 59 and start over
output: count up from current second
Why don't you use something like:
import time
sec = 0
while True:
print(59 - sec)
time.sleep(1)
sec = (sec + 1) % 60
Here is version with a defined function. It will countdown at defined seconds, taking sleep every seconds.
import time
def countdown(t_sec):
while t_sec:
mins, secs = divmod(t_sec, 60)
timeformat = '{:02d}'.format(secs)
print(timeformat)
time.sleep(1)
t_sec -= 1
countdown(59)

Python : Basic countdown timer & function() > int()

I'm trying to ucreate a timer function that runs in the background of my code and make it so I can use/check the time. What I mean by use/check, I'm trying to make it so I can call upon that timer function and use it as integer.
This is the code I currently have:
def timer():
for endtime in range(0, 15):
print(15 - endtime)
time.sleep(1)
def hall():
timer()
while (timer > 0):
do something
Currently only using print(15 - endtime) for confirmation it is counting down.
But what the code does now is execute the countdown and that's it, it never touches the while loop. And of course the last issue is I can't set a function to an int. So I'm looking for some way where I can check where the timer is at and use it in that while loop.
The way you do it, you'll going to have to use multithread.
Here is another, simpler approach :
On your script beginning, set a time_start variable with the number of seconds since the epoch using time.time()
Then when you need the number of elapsed seconds, use time.time() - time_start :
t_start = time.time()
# do whatever you'd like
t_current = int(time.time()-t_start) # this way you get the number of seconds elapsed since start.
You can put that in a function as well, defining t_start as a global variable.
import time
t_start = time.time()
def timer():
global t_start
print(str(int(time.time()-t_start)))
print('start')
time.sleep(2)
timer()
time.sleep(3)
timer()
import time
def timer(tim):
time.sleep(1)
print tim
def hall():
tim = 15
while (tim > 0):
print 'do something'
timer(tim)
tim-=1
Not the cleanest solution, but it will do what you need.
The problem with your code is that when you run hall(), Python first executes the whole of timer() (i.e. the whole for loop), and then moves on with the rest of the code (it can only do one thing at a time). Thus, by the time it reaches the while loop in hall(), timer is already 0.
So, you're going to have to do something about that timer so that it counts down once, and then it moves on to the do something part.
Something that you can do is this:
def hall():
for a in range(0, 15):
print(15 - a)
# do something
time.sleep(1)
This should work just fine (if you're only executing hall 15 times), and condenses your code to just one function.

How do you use KeyboardInterrupt without a try statement

I am trying to make a basic wage timer for my brother who just got a job... What I wanted to have was a while loop running the code waiting for someone to press enter (or some other key) ends the loop and give the current wage. I was hoping to KeyboardInterrupt but if there is an easier way to do it I would love to hear about it. How could I do this?
a keyboard interrupt is generated only when someone hits ctrl-C or similar.
it sounds like your plan was to have code something like:
from time import sleep
wage = 0
try:
while True:
wage = wage + hourly_rate
sleep(60 * 60) # an hour in seconds
except KeyboardInterrupt:
print('you earned', wage)
and then have someone hit ctrl-C? which would work with a try/except. but if you want someone just to hit the return key then instead of adding things up, do some maths:
from time import time
start = time() # time in seconds from some arbitrary date in 1970 (it's a standard)
input('hit return to get your wage!')
end = time()
elapsed = end - start # time that has passed in seconds between start and end
wage = hourly_rate * elapsed / (60 * 60) # convert from hourly
print('you earned', wage)
the first version is a bit optimistic as it adds each hour at the start. the second is more accurate.
ps congrats to your brother!

Categories

Resources