0

Due to my poor knowledge of Stack Overflow, Python and general writing skills I didn't specify the fact that I am using the pygame module. I'm very sorry for my lack of understanding and will aim to improve.

Started learning Python about 2-3 days ago. Recently encountered an issue with my implementation of a timer. I was using time.sleep(10), but later found that this actually pauses the code for 10 seconds, whereas I need it to count 10 seconds. Is there a way I could achieve this? Many thanks in advance.

EDIT: I understand now that the term 'timer' is probably not best suited. What I'm actually trying to do is create a cooldown of 10 seconds.

  • 3
    Would it make sense for your code to instead pause for 1 second ten times? Or check the time periodically to see if 10 seconds has elapsed? There are many strategies for problems like this, and choosing the correct one will require more details about what exactly you're trying to do. – Patrick Haugh Sep 07 '18 at 18:36
  • 3
    What do you mean with count 10 seconds and not to sleep ? Do you need alerts ? Do you need signals ? – Eric Nordelo Galiano Sep 07 '18 at 18:37
  • @PatrickHaugh Would this still pause the rest of my code for 1 second? –  Sep 07 '18 at 18:44
  • It sounds like you're looking for how to set a timer to do something later in a PyGame application. If you can [edit] your question to make that clear, and whether you're using a frame loop or and event loop to drive that application (or, if you don't understand that, enough of a [mcve] that we can figure it out ourselves), we can either write an answer or find a good duplicate with an existing one. – abarnert Sep 07 '18 at 18:47
  • 2
    As a guess, you're probably looking for [`pygame.time.set_timer`](https://www.pygame.org/docs/ref/time.html#pygame.time.set_timer). – abarnert Sep 07 '18 at 18:49
  • 1
    Possible duplicate of [Countdown timer in Pygame](https://stackoverflow.com/questions/30720665/countdown-timer-in-pygame) – skrx Sep 07 '18 at 18:51
  • 2
    "Timer" is a perfectly good term (and in fact the thing you're looking for may even be called a "timer" inside PyGame, or threading, or whatever). It's just that it's an _ambiguous_ word, so you need to give us more information so we know the context. – abarnert Sep 07 '18 at 18:52
  • 2
    You really should have mentioned that this is for PyGame. Doing time delays in a GUI program is quite different to doing it in a CLI program, so all of the currently existing answers to your question are irrelevant. – PM 2Ring Sep 07 '18 at 18:52
  • Perhaps `asyncio` library will suit your needs? – J0hn Sep 07 '18 at 19:04
  • @abarnert You've managed to get it spot on with your assumtion and I'm very sorry I didn't make my question clear! I will try out `pygame.time.set_timer` now, and report back. :) –  Sep 07 '18 at 19:29

3 Answers3

2

The issue I think you are running into is that your code runs sequentially. If you are looking to have some code running at the same time as the rest of your code runs (kind of like being in the background) you could use a Threading.

import threading
import time

def in_thread():
    print("Thread start")
    time.sleep(10)
    print("Thread end")

print("Start")
thread = threading.Thread(target=in_thread)
thread.start()
print("This continues")

However, if you are doing this as a cooldown system in a game I would recommend storing time.time(), which gives the current time in seconds, when the action is first taken. When they try to do the action again you can compare the current time to your stored time and see if they have passed the cooldown (time.time() - startTime > 10:).

Nelson
  • 58
  • 5
  • 1
    Awesome that you're making answers! I hope you wouldn't mind just a little pointer; You should explain how this answer is solving the OP-s problem. What is it doing? Why is it working? I'm not even sure this answers the question, and if you misinterpreted OPs question, without explaining your interpretation then you could end up with downvotes. Again: it's great to have you on board and that you're trying to help, and that's only what I'm trying to do too! – Andreas Storvik Strauman Sep 07 '18 at 18:52
  • @AndreasStorvikStrauman Thanks for the suggestions. I have updated my answer. – Nelson Sep 07 '18 at 18:59
  • Perfect! Great answer! – Andreas Storvik Strauman Sep 07 '18 at 19:00
1

Edit 2: Cooldown:

The following code

import time
import random
# Minimum time (in seconds) that it has to wait
for i in range(10):
    minimum_time=3
    tick=time.time()
    # How much time has passed since tick?
    passed_time=time.time()-tick
    # Sleep a random amount of time
    time.sleep(random.uniform(0,3))
    # Check if the passed time is less than the minimum time
    if passed_time<minimum_time:
        # If it is not passed enough time
        # then sleep the remaining time
        time.sleep(minimum_time-passed_time)

    print("{} seconds were used in this iteration of the loop, and it should be _at least_ 3".format(time.time()-tick))

Edit: This might be what you want:

import time
for i in range(1,11):
    print(i)
    time.sleep(1)

This one counts up from 1 to 10. You can reverse it by

import time
for i in reversed(range(1,11)):
    print(i)
    time.sleep(1)

First answer below

This is one way you could do a basic timer in python:

import time
# Get the current unix time stamp (that is time in seconds from 1970-01-01)
first=time.time()
# Sleep (pause the script) for 10 seconds
# (remove the line below and insert your code there instead)
time.sleep(10)
# Get the _now_ current time (also in seconds from 1970-01-01)
# and see how many seconds ago we did it last time
delta=time.time()-first
print(delta)

This now prints (approx) 10 because it took 10 seconds to run the above code.

You could also look at iPythons %timeit!

Addendum

You could also make this even bigger, and make a Timer class, like so:

import time
class Timer():
    def __init__(self):
        self.times=[]
        self._tick=0
    def tick(self):
        """ Call this to start timer """
        # Store the current time in _tick
        self._tick=time.time()
    def tock(self):
        """ Call this to stop timer """
        # Add the delta in the times-list
        self.times.append(time.time()-self._tick)
    def __str__(self):
        # This method is just so that the timer can be printed nicely
        # as further below
        return str(self.times)

Now you can just run t=Timer() followed by t.tick() and t.tock() to start and stop the timer respectively (multiple times(!)), and then print(t) to see all the recorded times. E.g.

t=Timer()
for i in range(4):
    t.tick()
    # Sleep (pause the script) for 10 seconds
    # (remove the line below and insert your code there instead)
    time.sleep(1)
    # Get the _now_ current time (also in seconds from 1970-01-01)
    # and see how many seconds ago we did it last time
    t.tock()
print(t)
0

you can set timer using threading.Timer:

class threading.Timer

A thread that executes a function after a specified interval has passed.

>>> import threading
>>> def hello():
...     print("Hello")
...
>>> t =threading.Timer(5, hello)
>>> t.start()
 Hello
Community
  • 1
  • 1
Hackaholic
  • 19,069
  • 5
  • 54
  • 72