Using the python time.sleep() method

Что такое класс Process в Python?

Класс Process в Python – это абстракция, которая настраивает другой процесс Python, предоставляет его для выполнения кода.

К классу Process принадлежат две важные функции – start() и join().

Сначала нам нужно написать функцию, которая будет запускаться процессом. Затем нам нужно создать экземпляр объекта процесса.

Если мы создадим объект процесса, ничего не произойдет, пока мы не скажем ему начать обработку с помощью функции start(). Затем процесс запустится и вернет свой результат. После этого мы говорим процессу завершиться через функцию join().

Без вызова функции join() процесс останется бездействующим и не завершится.

Поэтому, если вы создадите много процессов и не завершите их, вы можете столкнуться с нехваткой ресурсов. Тогда вам может потребоваться удалить их вручную.

Одна важная вещь: если вы хотите передать какой-либо аргумент через процесс, вам нужно использовать аргумент ключевого слова args. Следующий код будет полезен для понимания использования класса Process.

from multiprocessing import Process


def print_func(continent='Asia'):
    print('The name of continent is : ', continent)

if __name__ == "__main__":  # confirms that the code is under main function
    names = 
    procs = []
    proc = Process(target=print_func)  # instantiating without any argument
    procs.append(proc)
    proc.start()

    # instantiating process with arguments
    for name in names:
        # print(name)
        proc = Process(target=print_func, args=(name,))
        procs.append(proc)
        proc.start()

    # complete the processes
    for proc in procs:
        proc.join()

The Sleep-Wake Cycle

The quality of your sleep is determined by a process called the sleep-wake cycle.

There are two important parts of the sleep-wake cycle:

  1. Slow wave sleep (also known as deep sleep)
  2. REM sleep (REM stands for Rapid Eye Movement)

During slow wave sleep the body relaxes, breathing becomes more regular, blood pressure falls, and the brain becomes less responsive to external stimuli, which makes it more difficult to wake up. This phase is critical for renewal and repair of the body. During slow wave sleep, the pituitary gland releases growth hormone, which stimulates tissue growth and muscle repair. Researchers also believe that the body’s immune system is repaired during this stage. Slow wave sleep is particularly critical if you’re an athlete. You’ll often hear about professional athletes like Roger Federer or LeBron James sleeping 11 or 12 hours per night.

As one example of the impact of sleep on physical performance, consider a study researchers conducted on the Stanford basketball players. During this study, the players slept for at least ten hours per night (compared to their typical eight hours). During five weeks of extended sleep, the researchers measured the basketball players accuracy and speed compared to their previous levels. Free throw shooting percentage increased by 9 percent. Three point shooting percentage increased by 9.2 percent. And the players were 0.6 seconds faster when sprinting 80 meters. If you place heavy physical demands on your body, slow wave sleep is what helps you recover.

REM sleep is to the mind what slow wave sleep is to the body. The brain is relatively quiet during most sleep phases, but during REM your brain comes to life. REM sleep is when your brain dreams and re-organizes information. During this phase your brain clears out irrelevant information, boosts your memory by connecting the experiences of the last 24 hours to your previous experiences, and facilitates learning and neural growth. Your body temperature rises, your blood pressure increases, and your heart rate speeds up. Despite all of this activity, your body hardly moves. Typically, the REM phase occurs in short bursts about 3 to 5 times per night.

Without the slow wave sleep and REM sleep phases, the body literally starts to die. If you starve yourself of sleep, you can’t recover physically, your immune system weakens, and your brain becomes foggy. Or, as the researchers put it, sleep deprived individuals experience increased risk of viral infections, weight gain, diabetes, high blood pressure, heart disease, mental illness, and mortality.

To summarize: slow wave sleep helps you recover physically while REM sleep helps you recover mentally. The amount of time you spend in these phases tends to decrease with age, which means the quality of your sleep and your body’s ability to recover also decrease with age.

datetime.datetime

Объект datetime.datetime содержит всю информацию объектов datetime.date плюс datetime.time. Давайте приведем несколько примеров, для лучшего понимания разницы между этим объектом, и объектом datetime.date.

Python

import datetime

a = datetime.datetime(2017, 3, 5)
print(a) # datetime.datetime(2017, 3, 5, 0, 0)

b = datetime.datetime(2017, 3, 5, 12, 30, 10)
print(b) # datetime.datetime(2017, 3, 5, 12, 30, 10)

d = datetime.datetime(2017, 3, 5, 12, 30, 10)
print(d.year) # 2017
print(d.second) # 10
print(d.hour) # 12

1
2
3
4
5
6
7
8
9
10
11
12

importdatetime

a=datetime.datetime(2017,3,5)

print(a)# datetime.datetime(2017, 3, 5, 0, 0)

b=datetime.datetime(2017,3,5,12,30,10)

print(b)# datetime.datetime(2017, 3, 5, 12, 30, 10)

d=datetime.datetime(2017,3,5,12,30,10)

print(d.year)# 2017

print(d.second)# 10

print(d.hour)# 12

Мы видим, что datetime.datetime принимает несколько дополнительных аргументов: год, месяц, день, час, минута и секунда. Это также позволяет вам указывать информацию о микросекундах и часовом поясе. При работе с базами данных, данные типы объектов будут использоваться достаточно часто. Большую часть вашей работы, вам нужно будет конвертировать форматы date или datetime Python в форматы SQL datetime или timestamp

Обратите внимание на то, что today совместно с datetime.datetime использует два разных метода:

Python

import datetime

a = datetime.datetime.today()
print(a) # datetime.datetime(2017, 4, 5, 0, 16, 54, 989663)

b = datetime.datetime.now()
print(b) # datetime.datetime(2017, 4, 5, 0, 17, 8, 24239)

1
2
3
4
5
6
7

importdatetime

a=datetime.datetime.today()

print(a)# datetime.datetime(2017, 4, 5, 0, 16, 54, 989663)

b=datetime.datetime.now()

print(b)# datetime.datetime(2017, 4, 5, 0, 17, 8, 24239)

Модуль datetime содержит другой метод, под названием strftime. Этот метод позволяет разработчику создавать строку, отображающую время в более понятной для человека форме. Существует целая таблица параметров форматирования, с которой рекомендуется ознакомиться в документации Python, в . Давайте взглянем на несколько примеров, показывающих всю полезность данного метода:

Python

import datetime

a = datetime.datetime.today().strftime(«%Y%m%d»)
print(a) # ‘20170405’

today = datetime.datetime.today()
print( today.strftime(«%m/%d/%Y») ) # ’04/05/2017′

print( today.strftime(«%Y-%m-%d-%H.%M.%S») ) # 2017-04-05-00.18.00

1
2
3
4
5
6
7
8
9

importdatetime

a=datetime.datetime.today().strftime(«%Y%m%d»)

print(a)# ‘20170405’

today=datetime.datetime.today()

print(today.strftime(«%m/%d/%Y»))# ’04/05/2017′

print(today.strftime(«%Y-%m-%d-%H.%M.%S»))# 2017-04-05-00.18.00

Первый пример – это скорее хитрость. В нем показано, как конвертировать сегодняшний объект datetime в строку, следующую за форматом YYYYMMDD (ГГГГММДД). Второй пример более наглядный.

В нем мы присваиваем объект datetime переменной под названием today и применяем два разных параметра форматирования строки. Первый параметр добавляет косые черточки между элементами datetime, а также перегруппировывает datetime, теперь он делится на месяц, день и год. В последнем примере мы создаем временную отметку, которая следует типичному формату: YYYY-MM-DD.HH.MM.SS. Если вам нужно указать год как двухзначный (“YY”), вы можете заменить %Y на %y.

Best time to go to sleep

Share on PinterestA person’s age can determine the amount of sleep that they require.

In general, the body and brain slow down as it gets dark and start to wake up as the sun rises.

There is some evidence to suggest that early bedtimes are better for people. One study involving 1,197 Japanese workers found that those who went to bed later were more likely to have depressive symptoms. However, sleep duration may have contributed to these symptoms, as the participants who went to bed later often got less sleep.

Another study found that people who stated a preference for going to sleep later also had higher levels of repetitive negative thinking, such as dwelling on problems or bad experiences. Importantly, this also affects how much sleep a person gets.

It may be best to understand how much sleep the average person needs and then use that number to set a bedtime.

Adding a Python sleep() Call With GUIs

Command-line applications aren’t the only place where you might need to add Python calls. When you create a Graphical User Interface (GUI), you’ll occasionally need to add delays. For example, you might create an FTP application to download millions of files, but you need to add a call between batches so you don’t bog down the server.

GUI code will run all its processing and drawing in a main thread called the event loop. If you use inside of GUI code, then you’ll block its event loop. From the user’s perspective, the application could appear to freeze. The user won’t be able to interact with your application while it’s sleeping with this method. (On Windows, you might even get an alert about how your application is now unresponsive.)

Fortunately, there are other methods you can use besides . In the next few sections, you’ll learn how to add Python calls in both Tkinter and wxPython.

Подклассы потоков

При запуске Thread выполняет базовую инициализацию и затем вызывает свой метод run(). Он в свою очередь вызывает целевую функцию, переданную конструктору. Чтобы создать подкласс Thread, переопределите run().

import threading
import logging

logging.basicConfig(level=logging.DEBUG,
                    format='(%(threadName)-10s) %(message)s',
                    )

class MyThread(threading.Thread):

    def run(self):
        logging.debug('running')
        return

for i in range(5):
    t = MyThread()
    t.start()

Возвращаемое значение метода run() игнорируется.

$ python threading_subclass.py

(Thread-1  ) running
(Thread-2  ) running
(Thread-3  ) running
(Thread-4  ) running
(Thread-5  ) running

Значения args и kwargs, передаваемые в конструктор Thread, сохраняются в private переменных. Поэтому к ним трудно получить доступ из подкласса.

Для передачи аргументов пользовательскому потоку, переопределите конструктор, чтобы сохранить значения в атрибуте экземпляра.

import threading
import logging

logging.basicConfig(level=logging.DEBUG,
                    format='(%(threadName)-10s) %(message)s',
                    )

class MyThreadWithArgs(threading.Thread):

    def __init__(self, group=None, target=None, name=None,
                 args=(), kwargs=None, verbose=None):
        threading.Thread.__init__(self, group=group, target=target, name=name,
                                  verbose=verbose)
        self.args = args
        self.kwargs = kwargs
        return

    def run(self):
        logging.debug('running with %s and %s', self.args, self.kwargs)
        return

for i in range(5):
    t = MyThreadWithArgs(args=(i,), kwargs={'a':'A', 'b':'B'})
    t.start()

MyThreadWithArgs использует тот же API, что и Thread. Но другой класс может легко изменить метод конструктора, чтобы принимать другие аргументы, связанные с назначением потока.

$ python threading_subclass_args.py

(Thread-1  ) running with (0,) and {'a': 'A', 'b': 'B'}
(Thread-2  ) running with (1,) and {'a': 'A', 'b': 'B'}
(Thread-3  ) running with (2,) and {'a': 'A', 'b': 'B'}
(Thread-4  ) running with (3,) and {'a': 'A', 'b': 'B'}
(Thread-5  ) running with (4,) and {'a': 'A', 'b': 'B'}

Daemon потоки non-daemon

До этого момента примеры программ ожидали, пока все потоки не завершат свою работу. Иногда программы порождают такой поток, как демон. Он работает, не блокируя завершение основной программы.

Использование демона полезно, если не удается прервать поток или завершить его в середине работы, не потеряв и не повредив при этом данные.

Чтобы пометить поток как demon, вызовите метод setDaemon() с логическим аргументом. По умолчанию потоки не являются «демонами», поэтому передача в качестве аргумента значения True включает режим demon.

import threading
import time
import logging

logging.basicConfig(level=logging.DEBUG,
                    format='(%(threadName)-10s) %(message)s',
                    )

def daemon():
    logging.debug('Starting')
    time.sleep(2)
    logging.debug('Exiting')

d = threading.Thread(name='daemon', target=daemon)
d.setDaemon(True)

def non_daemon():
    logging.debug('Starting')
    logging.debug('Exiting')

t = threading.Thread(name='non-daemon', target=non_daemon)

d.start()
t.start()

Обратите внимание, что в выводимых данных отсутствует сообщение «Exiting» от потока-демона. Все потоки, не являющиеся «демонами» (включая основной поток), завершают работу до того, как поток-демон выйдет из двухсекундного сна

$ python threading_daemon.py

(daemon    ) Starting
(non-daemon) Starting
(non-daemon) Exiting

Чтобы дождаться завершения работы потока-демона, используйте метод join().

import threading
import time
import logging

logging.basicConfig(level=logging.DEBUG,
                    format='(%(threadName)-10s) %(message)s',
                    )

def daemon():
    logging.debug('Starting')
    time.sleep(2)
    logging.debug('Exiting')

d = threading.Thread(name='daemon', target=daemon)
d.setDaemon(True)

def non_daemon():
    logging.debug('Starting')
    logging.debug('Exiting')

t = threading.Thread(name='non-daemon', target=non_daemon)

d.start()
t.start()

d.join()
t.join()

Метод join() позволяет demon вывести сообщение «Exiting».

$ python threading_daemon_join.py

(daemon    ) Starting
(non-daemon) Starting
(non-daemon) Exiting
(daemon    ) Exiting

Также можно передать аргумент задержки (количество секунд, в течение которых поток будет неактивным).

import threading
import time
import logging

logging.basicConfig(level=logging.DEBUG,
                    format='(%(threadName)-10s) %(message)s',
                    )

def daemon():
    logging.debug('Starting')
    time.sleep(2)
    logging.debug('Exiting')

d = threading.Thread(name='daemon', target=daemon)
d.setDaemon(True)

def non_daemon():
    logging.debug('Starting')
    logging.debug('Exiting')

t = threading.Thread(name='non-daemon', target=non_daemon)

d.start()
t.start()

d.join(1)
print 'd.isAlive()', d.isAlive()
t.join()

Истекшее время ожидания меньше, чем время, в течение которого поток-демон спит. Поэтому поток все еще «жив» после того, как метод join() продолжит свою работу.

$ python threading_daemon_join_timeout.py

(daemon    ) Starting
(non-daemon) Starting
(non-daemon) Exiting
d.isAlive() True

The 2-Process Model of Sleep Regulation

In 1982, Dr. Alexander Borbely published an article in the journal Human Neurobiology describing something he called the 2-process model of sleep regulation. This conceptual framework for sleep describes two processes that occur simultaneously to regulate sleep and wake states.

Process 1 is sleep pressure. Basically, sleep pressure mounts from the moment you wake up, to the time when you go to sleep. While you’re sleeping, pressure decreases. If you get a full night of sleep, you start the next day with low sleep pressure.

Process 2 is wake drive, which counteracts sleep pressure and is controlled by a 24-hour rhythm that repeats in a wave-pattern.

It’s important to understand this process because it helps reveal an important point about sleep in our modern world that I learned from sleep scientist Dan Pardi:

For millions of years, humans and our ancestors have evolved to sleep at night (when it is dark) and wake during the day (when it is light). However, in the modern world, we work inside all day, often in areas that are darker than the outside world. And then, at night, we look at bright screens and televisions. Low light during the day, more light at night: It’s the opposite of naturally occurring cycles and it seems quite likely that it could mess up your wake rhythm and circadian rhythm.

The result of this shift? Drowsiness and impaired function through the day. We’ll talk more in just a minute about how to sleep better, including actionable steps you can take to anchor your rhythm, but it pretty much comes down to this: Use common-sense light habits. Get outdoor light exposure during the day, and turn down the lights and turn off your screens after dark.

Timezone Constants¶

The offset of the local DST timezone, in seconds west of UTC, if one is defined.
This is negative if the local DST timezone is east of UTC (as in Western Europe,
including the UK). Only use this if is nonzero. See note below.

Nonzero if a DST timezone is defined. See note below.

The offset of the local (non-DST) timezone, in seconds west of UTC (negative in
most of Western Europe, positive in the US, zero in the UK). See note below.

A tuple of two strings: the first is the name of the local non-DST timezone, the
second is the name of the local DST timezone. If no DST timezone is defined,
the second string should not be used. See note below.

Note

For the above Timezone constants (, , ,
and ), the value is determined by the timezone rules in effect
at module load time or the last time is called and may be incorrect
for times in the past. It is recommended to use the and
results from to obtain timezone information.

See also

Module

More object-oriented interface to dates and times.

Module

Internationalization services. The locale setting affects the interpretation
of many format specifiers in and .

Module

General calendar-related functions. is the
inverse of from this module.

Footnotes

The use of is now deprecated, but the escape that expands to the
preferred hour/minute offset is not supported by all ANSI C libraries. Also, a
strict reading of the original 1982 RFC 822 standard calls for a two-digit
year (%y rather than %Y), but practice moved to 4-digit years long before the
year 2000. After that, RFC 822 became obsolete and the 4-digit year has
been first recommended by RFC 1123 and then mandated by RFC 2822.

Пользовательские Классы таймера Python

Вы можете создать свой собственный класс таймера, чтобы делать все в соответствии с вашими потребностями. Одним из главных преимуществ создания пользовательского класса является то, что вы можете управлять всем временем в одной строке. Вам не нужно каждый раз импортировать класс time и записывать ссылки. Кроме того, вы можете сбросить свои данные и записать все прошлые исполнения времени, чтобы выбрать лучший алгоритм для вас.

В этом разделе будет создан пользовательский класс для управления временем и регистрации всех временных различий в ваших кодах. Давайте нырнем прямо в него –

<сильный>Timer.py –

Начнем с импорта модуля времени. Затем инициализируйте класс таймера python и начните определять атрибуты и методы. До сих пор мы включали только базовый атрибут, чтобы сохранить начальную ссылку класса. Чтобы сделать его более сложным, вы можете создать несколько атрибутов. На данный момент существует три метода, перечисленных ниже –

  1. start – (Необязательно) Чтобы запустить таймер.
  2. log – Регистрировать текущее прошедшее время относительно времени начала.
  3. milestone – Сбросить таймер и начать его отсчет с 0.
import time

class Timer:

    def __init__(self):
       .time()

    def start(self):
       .time()

    def log(self):
       .time() - self.start
        print('Time log -',logger)

    def milestone(self):
       .time()

<сильный>example.py –

Примеры использования вышеуказанного класса приведены ниже. Как вы можете видеть, вы можете сохранить свой код чистым, создав пользовательский класс таймера и повысив гибкость.

import timer
.Timer()
for i in range(1000000):
	pass

time.log()
for i in range(1000000):
	pass

time.log()

Выход –

Using Event().wait

The Event().wait method comes from the threading module. Event.wait() method will halt the execution of any process for the number of seconds it takes as an argument. The working of Event is shown in the example below:

Example:

The code is using Event().wait(5).The number 5 is the number of seconds the code will delay to go to the next line that calls the function display(). Once the 5 seconds are done, the function display() will be called, and the message will be printed inside in the terminal.

from threading import Event

print('Code Execution Started')

def display():
    print('Welcome to Guru99 Tutorials')


Event().wait(5) 
display()

Output:

Code Execution Started
Welcome to Guru99 Tutorials

Вызов sleep() через time.sleep()

В Python есть встроенная поддержка для погружения программы в сон. У модуля есть функция , что позволяет отсрочить выполнение вызываемого потока на указанное количество секунд.

Мы собрали ТОП Книг для Python программиста которые помогут быстро изучить язык программирования Python.
Список книг: Книги по Python

Далее дан пример использования :

Python

import time
time.sleep(3) # Сон в 3 секунды

1
2

importtime

time.sleep(3)# Сон в 3 секунды

При запуске кода из консоли, задержку нужно проводить перед вводом нового оператора в REPL.

Вы можете протестировать, как долго продлиться сон с помощью модуля Python timeit:

Shell

$ python3 -m timeit -n 3 «import time; time.sleep(3)»
3 loops, best of 3: 3 sec per loop

1
2

$python3-mtimeit-n3″import time; time.sleep(3)»

3loops,best of33sec per loop

Здесь модуль запускается с параметром , что указывает , сколько раз выполнять последующий оператор. Можно заметить, что выполнил оператор 3 раза, а лучшее время длилось 3 секунды, чего и следовало ожидать.

По умолчанию будет запускать код миллион раз. Если бы вы запустили вышеуказанный код, оставив значение по умолчанию, тогда при 3 секундах на итерацию код завис бы примерно на 34 дня! У модуля есть несколько других настроек для командной строки, с которыми можно ознакомиться в .

Создадим что-то более практичное. Системному администратору всегда нужно быть в курсе, если какой-то из сайтов упал. Вы бы хотели иметь возможность проверить код состояния сайта регулярно, но запрашивать веб сервер постоянно нельзя, ведь это сильно повлияет на производительность. В Python одним из простых способов совершить такую проверку является использование системного вызова :

Python

import time
import urllib.request
import urllib.error

def uptime_bot(url):
while True:
try:
conn = urllib.request.urlopen(url)
except urllib.error.HTTPError as e:
# Отправка admin / log
print(f’HTTPError: {e.code} для {url}’)
except urllib.error.URLError as e:
# Отправка admin / log
print(f’URLError: {e.code} для {url}’)
else:
# Сайт поднят
print(f'{url} поднят’)
time.sleep(60)

if __name__ == ‘__main__’:
url = ‘http://www.google.com/py’
uptime_bot(url)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

19
20
21
22

importtime

importurllib.request

importurllib.error

defuptime_bot(url)

whileTrue

try

conn=urllib.request.urlopen(url)

excepturllib.error.HTTPError ase

# Отправка admin / log

print(f’HTTPError: {e.code} для {url}’)

excepturllib.error.URLError ase

# Отправка admin / log

print(f’URLError: {e.code} для {url}’)

else

# Сайт поднят

print(f'{url} поднят’)

if__name__==’__main__’

url=’http://www.google.com/py’

uptime_bot(url)

Здесь создается , что принимает URL в качестве аргумента. Затем функция пытается открыть данный URL c . При возникновении или программа перехватывает ошибку и выводит на экран. На практике вам, скорее всего, придется зафиксировать ошибку и отправить письмо веб-мастеру или системному администратору.

Если ошибок нет, код спокойно выполняется. Вне зависимости от того, что произойдет, программа уходит в сон на 60 секунд. Это значит, что доступ к сайту будет раз за минуту. URL, используемый в примере, содержит ошибки. Ежеминутный вывод на консоли выглядит следующим образом:

Shell

HTTPError: 404 для http://www.google.com/py

1 HTTPError404дляhttpwww.compy

Попробуйте обновить код, используя проверенный хороший URL, к примеру https://www.google.com/. После этого вы можете перезапустить программу и проверить, что изменилось. Также можно попробовать обновить код для отправки сообщения или записи об ошибке. Для получения более подробной информации можете ознакомиться со статьями отправка писем smtp и логирование.

Использование time.sleep() в threading

Python является хорошим примером использования . Модуль логирования logging является потоко-безопасным, поэтому в данном примере он будет полезнее, чем операторы . В основе следующего кода лежит данный пример:

Python

import logging
import threading
import time

def worker(arg):
while not arg:
logging.debug(«рабочий поток вносится»)
time.sleep(1)

def main():
logging.basicConfig(
level=logging.DEBUG,
format=»%(relativeCreated)6d %(threadName)s %(message)s»
)
info = {«stop»: False}
thread = threading.Thread(target=worker, args=(info,))
thread_two = threading.Thread(target=worker, args=(info,))
thread.start()
thread_two.start()

while True:
try:
logging.debug(«Добавление из главного потока»)
time.sleep(0.75)
except KeyboardInterrupt:
info = True
logging.debug(‘Остановка’)
break
thread.join()
thread_two.join()

if __name__ == «__main__»:
main()

1
2
3
4
5
6
7

9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

25
26
27
28
29
30
31
32
33

importlogging

importthreading

importtime

defworker(arg)

whilenotarg»stop»

logging.debug(«рабочий поток вносится»)

defmain()

logging.basicConfig(

level=logging.DEBUG,

format=»%(relativeCreated)6d %(threadName)s %(message)s»

)

info={«stop»False}

thread=threading.Thread(target=worker,args=(info,))

thread_two=threading.Thread(target=worker,args=(info,))

thread.start()

thread_two.start()

whileTrue

try

logging.debug(«Добавление из главного потока»)

exceptKeyboardInterrupt

info»stop»=True

logging.debug(‘Остановка’)

break

thread.join()

thread_two.join()

if__name__==»__main__»

main()

Здесь для создания двух потоков используется модуль Python . Также создается объект входа, что будет вводить в . Затем начинаются оба потока и инициируется цикл для каждого входа из главного потока. Для фиксирования пользователя используется при нажатии .

Попробуйте запустить вышеуказанный код в терминале. Ваш вывод должен походить на следующий:

Shell

2 Thread-1 рабочий поток вносится
4 Thread-2 рабочий поток вносится
4 MainThread Добавление из главного потока
755 MainThread Добавление из главного потока
1004 Thread-1 рабочий поток вносится
1006 Thread-2 рабочий поток вносится
1506 MainThread Добавление из главного потока
2005 Thread-1 рабочий поток вносится
2007 Thread-2 рабочий поток вносится
2257 MainThread Добавление из главного потока
3007 Thread-1 рабочий поток вносится
3008 MainThread Добавление из главного потока

1
2
3
4
5
6
7
8
9
10
11
12

2Thread-1рабочийпотоквносится

4Thread-2рабочийпотоквносится

4MainThreadДобавлениеизглавногопотока

755MainThreadДобавлениеизглавногопотока

1004Thread-1рабочийпотоквносится

1006Thread-2рабочийпотоквносится

1506MainThreadДобавлениеизглавногопотока

2005Thread-1рабочийпотоквносится

2007Thread-2рабочийпотоквносится

2257MainThreadДобавлениеизглавногопотока

3007Thread-1рабочийпотоквносится

3008MainThreadДобавлениеизглавногопотока

Когда каждый поток работает, а затем уходит в сон, выходные данные выводятся в консоль. Теперь, разобрав пример, вы сможете использовать данные концепции в своем собственном коде.

Вызов sleep() в Tkinter и wxPython

Вызовы в Python можно добавить не только для приложений командной строки. При создании графического пользовательского интерфейса (GUI) периодически нужно добавлять отсрочки. К примеру, при создании приложения FTP для скачивания около миллиона файлов будет разумно добавить вызов между партиями, чтобы снизить нагрузку на сервер.

GUI код выполнит всю обработку в основном потоке, называемом циклом обработки событий, или event loop. При использовании внутри кода GUI заблокируется цикл обработки событий.

К счастью, помимо , можно использовать некоторые другие методы специально для этой задачи. Далее мы рассмотрим, как добавить вызовы в Tkinter и wxPython.

Adding a Python sleep() Call With Threads

There are also times when you might want to add a Python call to a thread. Perhaps you’re running a migration script against a database with millions of records in production. You don’t want to cause any downtime, but you also don’t want to wait longer than necessary to finish the migration, so you decide to use threads.

Note: Threads are a method of doing concurrency in Python. You can run multiple threads at once to increase your application’s throughput. If you’re not familiar with threads in Python, then check out An Intro to Threading in Python.

To prevent customers from noticing any kind of slowdown, each thread needs to run for a short period and then sleep. There are two ways to do this:

  1. Use as before.
  2. Use from the module.

Let’s start by looking at .

Объекты потоков

Самый простой способ использовать поток — создать его с помощью целевой функции и запустить с помощью метода start().

import threading

def worker():
    """thread worker function"""
    print 'Worker'
    return

threads = []
for i in range(5):
    t = threading.Thread(target=worker)
    threads.append(t)
    t.start()


Результат работы программы – пять строк со строкой «Worker»:

$ python threading_simple.py

Worker
Worker
Worker
Worker
Worker

В приведенном ниже примере в качестве аргумента потоку передается число для вывода.

import threading

def worker(num):
    """thread worker function"""
    print 'Worker: %s' % num
    return

threads = []
for i in range(5):
    t = threading.Thread(target=worker, args=(i,))
    threads.append(t)
    t.start()

Целочисленный аргумент теперь включен в сообщение, выводимое каждым потоком:

$ python -u threading_simpleargs.py

Worker: 0
Worker: 1
Worker: 2
Worker: 3
Worker: 4

Frequently Asked Questions

Great question.

The sleep function actually takes a floating point number as an argument, not an integer.

And that means, you can pass any fraction of a second as an argument.

For example:

Q: How to use the sleep function to sleep until a specific time?

This is a very common question.

Depending on what you are trying to do, there are two different ways to achieve this.

The straight-forward way is to precompute the delay (in seconds) until that specific time before you call the sleep function.

Another way is to use the function from the event module.

If what you are trying to do is to block a thread until a condition happens, it is much better to use wait().

Q: How is sleep actually implemented?

This is a fantastic question.

sleep is not actually implemented by Python.

Well, it is, but it is simply a wrapper around something else that is implemented by the Operating System.

All Operating Systems have a Sleep() system call.

If you don’t know what a System Call is, then you should!

here is the book that I recommend for learning about Operating Systems concepts.

But either way, you can think of a System Call as an API or an interface that the OS provides for user-space programs to interact with the OS.

So what does an OS do when it receives a Sleep System Call?

Basically what the OS will do is that it will suspend the process (your program) from being scheduled on the CPU for the time period that you specified.

Notice that this is completely different from adding delay using a dummy for loop that does nothing (which is something you should NEVER do).

In the case of a dummy for loop, your process is actually still running on the CPU.

But in the case of Sleep(), your process will be effectively dormant for a while until the OS starts scheduling it again on the CPU.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector