Home > Backend Development > Python Tutorial > How Can I Pause My Python Script's Execution for a Specific Duration?

How Can I Pause My Python Script's Execution for a Specific Duration?

Barbara Streisand
Release: 2024-12-14 00:12:15
Original
858 people have browsed it

How Can I Pause My Python Script's Execution for a Specific Duration?

Delaying Execution in Python with time.sleep()

A common need in Python scripts is to introduce a time delay, such as for intervals between tasks or pausing for user input. This can be achieved using the time.sleep() function.

To implement a delay, specify the desired amount of time (in seconds) as the argument to time.sleep(). For example, to delay execution by 2.5 seconds:

import time

time.sleep(2.5)
Copy after login

This will cause the script to pause for the specified duration before continuing to the next line of code.

Alternatively, to execute a task at regular intervals, employ a loop with a delay:

import time

while True:
    print("This prints once a minute.")
    time.sleep(60)  # Delay for 1 minute (60 seconds).
Copy after login

In this example, the loop will continuously print a message every minute, with the delay provided by time.sleep(60).

The above is the detailed content of How Can I Pause My Python Script's Execution for a Specific Duration?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template