Hướng dẫn how to set time interval in python - cách đặt khoảng thời gian trong python

Đây có thể là đoạn trích chính xác mà bạn đang tìm kiếm:

import threading

def set_interval(func, sec):
    def func_wrapper():
        set_interval(func, sec)
        func()
    t = threading.Timer(sec, func_wrapper)
    t.start()
    return t

Hướng dẫn how to set time interval in python - cách đặt khoảng thời gian trong python

Nhanh

Huy hiệu vàng 13K553 Huy hiệu bạc79 Huy hiệu đồng5 gold badges53 silver badges79 bronze badges

Đã trả lời ngày 26 tháng 12 năm 2012 lúc 1:59Dec 26, 2012 at 1:59

Stamatstamatstamat

1.78421 huy hiệu bạc26 Huy hiệu đồng21 silver badges26 bronze badges

5

Đây là phiên bản mà bạn có thể bắt đầu và dừng lại. Nó không chặn. Cũng không có trục trặc vì lỗi thời gian thực thi không được thêm vào (ví dụ như thực thi thời gian dài với khoảng thời gian rất ngắn làm âm thanh chẳng hạn)

import time, threading

StartTime=time.time()

def action() :
    print('action ! -> time : {:.1f}s'.format(time.time()-StartTime))


class setInterval :
    def __init__(self,interval,action) :
        self.interval=interval
        self.action=action
        self.stopEvent=threading.Event()
        thread=threading.Thread(target=self.__setInterval)
        thread.start()

    def __setInterval(self) :
        nextTime=time.time()+self.interval
        while not self.stopEvent.wait(nextTime-time.time()) :
            nextTime+=self.interval
            self.action()

    def cancel(self) :
        self.stopEvent.set()

# start action every 0.6s
inter=setInterval(0.6,action)
print('just after setInterval -> time : {:.1f}s'.format(time.time()-StartTime))

# will stop interval in 5s
t=threading.Timer(5,inter.cancel)
t.start()

Đầu ra là:

just after setInterval -> time : 0.0s
action ! -> time : 0.6s
action ! -> time : 1.2s
action ! -> time : 1.8s
action ! -> time : 2.4s
action ! -> time : 3.0s
action ! -> time : 3.6s
action ! -> time : 4.2s
action ! -> time : 4.8s

Đã trả lời ngày 9 tháng 2 năm 2018 lúc 15:44Feb 9, 2018 at 15:44

Doomdoomdoom

3.0504 huy hiệu vàng26 Huy hiệu bạc40 Huy hiệu đồng4 gold badges26 silver badges40 bronze badges

3

Chỉ cần giữ nó đẹp và đơn giản.

import threading

def setInterval(func,time):
    e = threading.Event()
    while not e.wait(time):
        func()

def foo():
    print "hello"

# using
setInterval(foo,5)

# output:
hello
hello
.
.
.

Chỉnh sửa: Mã này không chặn

import threading

class ThreadJob(threading.Thread):
    def __init__(self,callback,event,interval):
        '''runs the callback function after interval seconds

        :param callback:  callback function to invoke
        :param event: external event for controlling the update operation
        :param interval: time in seconds after which are required to fire the callback
        :type callback: function
        :type interval: int
        '''
        self.callback = callback
        self.event = event
        self.interval = interval
        super(ThreadJob,self).__init__()

    def run(self):
        while not self.event.wait(self.interval):
            self.callback()



event = threading.Event()

def foo():
    print "hello"

k = ThreadJob(foo,event,2)
k.start()

print "It is non-blocking"

Đã trả lời ngày 27 tháng 6 năm 2015 lúc 12:38Jun 27, 2015 at 12:38

Hướng dẫn how to set time interval in python - cách đặt khoảng thời gian trong python

DarXtrixDarXtrixdarxtrix

1.9822 Huy hiệu vàng22 Huy hiệu bạc 30 Huy hiệu Đồng2 gold badges22 silver badges30 bronze badges

2

Thay đổi câu trả lời của NailXX một chút và bạn đã nhận được câu trả lời!Nailxx's answer a bit and you got the answer!

from threading import Timer

def hello():
    print "hello, world"
    Timer(30.0, hello).start()

Timer(30.0, hello).start() # after 30 seconds, "hello, world" will be printed

Hans sau đó

10,8K3 Huy hiệu vàng32 Huy hiệu bạc 50 Huy hiệu Đồng3 gold badges32 silver badges50 bronze badges

Đã trả lời ngày 3 tháng 11 năm 2013 lúc 11:49Nov 3, 2013 at 11:49

2

Mô -đun

just after setInterval -> time : 0.0s
action ! -> time : 0.6s
action ! -> time : 1.2s
action ! -> time : 1.8s
action ! -> time : 2.4s
action ! -> time : 3.0s
action ! -> time : 3.6s
action ! -> time : 4.2s
action ! -> time : 4.8s
4 cung cấp các khả năng này cho mã Python chung. Tuy nhiên, như tài liệu của nó cho thấy, nếu mã của bạn được đa luồng thì có thể có ý nghĩa hơn khi sử dụng lớp
just after setInterval -> time : 0.0s
action ! -> time : 0.6s
action ! -> time : 1.2s
action ! -> time : 1.8s
action ! -> time : 2.4s
action ! -> time : 3.0s
action ! -> time : 3.6s
action ! -> time : 4.2s
action ! -> time : 4.8s
5 thay thế.

Đã trả lời ngày 23 tháng 4 năm 2010 lúc 8:03Apr 23, 2010 at 8:03

Eli Benderskyeli BenderskyEli Bendersky

254K87 Huy hiệu vàng344 Huy hiệu bạc408 Huy hiệu đồng87 gold badges344 silver badges408 bronze badges

0

Tôi nghĩ rằng đây là những gì bạn sau:

#timertest.py
import sched, time
def dostuff():
  print "stuff is being done!"
  s.enter(3, 1, dostuff, ())

s = sched.scheduler(time.time, time.sleep)
s.enter(3, 1, dostuff, ())
s.run()

Nếu bạn thêm một mục khác vào bộ lập lịch ở cuối phương thức lặp lại, nó sẽ tiếp tục.

Đã trả lời ngày 4 tháng 1 năm 2012 lúc 17:32Jan 4, 2012 at 17:32

Visumvisumvisum

3473 Huy hiệu bạc9 Huy hiệu Đồng3 silver badges9 bronze badges

3

Tôi sử dụng lịch trình để tạo chức năng

just after setInterval -> time : 0.0s
action ! -> time : 0.6s
action ! -> time : 1.2s
action ! -> time : 1.8s
action ! -> time : 2.4s
action ! -> time : 3.0s
action ! -> time : 3.6s
action ! -> time : 4.2s
action ! -> time : 4.8s
6

import functools
import sched, time

s = sched.scheduler(time.time, time.sleep)

def setInterval(sec):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*argv, **kw):
            setInterval(sec)(func)
            func(*argv, **kw)
        s.enter(sec, 1, wrapper, ())
        return wrapper
    s.run()
    return decorator


@setInterval(sec=3)
def testInterval():
  print ("test Interval ")

testInterval()

Đã trả lời ngày 26 tháng 5 năm 2020 lúc 19:28May 26, 2020 at 19:28

Alaa aqeelalaa aqeelAlaa Aqeel

5767 Huy hiệu bạc16 Huy hiệu Đồng7 silver badges16 bronze badges

1

SetInterval đơn giản

________số 8

Đã trả lời ngày 7 tháng 1 năm 2019 lúc 7:33Jan 7, 2019 at 7:33

Hướng dẫn how to set time interval in python - cách đặt khoảng thời gian trong python

Tan Nguyễn NguyễnTan Nguyen

6956 Huy hiệu bạc8 Huy hiệu Đồng6 silver badges8 bronze badges

2

Phương pháp trên không hoàn toàn làm điều đó cho tôi vì tôi cần có thể hủy khoảng thời gian. Tôi đã biến chức năng thành một lớp và đưa ra những điều sau đây:

class setInterval():
    def __init__(self, func, sec):
        def func_wrapper():
            self.t = threading.Timer(sec, func_wrapper)
            self.t.start()
            func()
        self.t = threading.Timer(sec, func_wrapper)
        self.t.start()

    def cancel(self):
        self.t.cancel()

Đã trả lời ngày 4 tháng 10 năm 2016 lúc 0:00Oct 4, 2016 at 0:00

Hầu hết các câu trả lời trên không tắt luồng đúng cách. Trong khi sử dụng sổ ghi chép Jupyter, tôi nhận thấy rằng khi một ngắt rõ ràng được gửi, các luồng vẫn đang chạy và tệ hơn, chúng sẽ tiếp tục nhân bắt đầu từ 1 luồng chạy, 2, 4, v.v. Xử lý các ngắt bằng cách chạy một vòng lặp vô hạn trong luồng chính để lắng nghe các sự kiện Sigint và Sigterm

  • Không trôi dạt
  • Có thể hủy bỏ
  • Xử lý Sigint và Sigterm rất tốt
  • Không tạo một chủ đề mới cho mỗi lần chạy

Hãy thoải mái đề xuất những cải tiến

import time, threading

StartTime=time.time()

def action() :
    print('action ! -> time : {:.1f}s'.format(time.time()-StartTime))


class setInterval :
    def __init__(self,interval,action) :
        self.interval=interval
        self.action=action
        self.stopEvent=threading.Event()
        thread=threading.Thread(target=self.__setInterval)
        thread.start()

    def __setInterval(self) :
        nextTime=time.time()+self.interval
        while not self.stopEvent.wait(nextTime-time.time()) :
            nextTime+=self.interval
            self.action()

    def cancel(self) :
        self.stopEvent.set()

# start action every 0.6s
inter=setInterval(0.6,action)
print('just after setInterval -> time : {:.1f}s'.format(time.time()-StartTime))

# will stop interval in 5s
t=threading.Timer(5,inter.cancel)
t.start()
0

Đã trả lời ngày 26 tháng 2 năm 2019 lúc 11:49Feb 26, 2019 at 11:49

Hướng dẫn how to set time interval in python - cách đặt khoảng thời gian trong python

PirateApppirateAppPirateApp

4.7913 Huy hiệu vàng 50 Huy hiệu bạc76 Huy hiệu Đồng3 gold badges50 silver badges76 bronze badges

3

Trong các giải pháp trên nếu một tình huống phát sinh khi chương trình ngừng hoạt động, không có gì đảm bảo rằng nó sẽ tắt một cách duyên dáng, luôn luôn khuyên bạn nên tắt một chương trình thông qua một vụ giết người mềm, hầu hết trong số họ không có chức năng nào để dừng lại tôi đã tìm thấy một bài viết hay Trên phương tiện được viết bởi Sankalp, trong đó giải quyết cả hai vấn đề này (chạy các nhiệm vụ định kỳ trong Python) tham khảo liên kết đính kèm để có được cái nhìn sâu sắc hơn. Trong mẫu dưới đây, thư viện có tên tín hiệu được sử dụng để theo dõi giết chết là tiêu diệt mềm hoặc giết cứng

import time, threading

StartTime=time.time()

def action() :
    print('action ! -> time : {:.1f}s'.format(time.time()-StartTime))


class setInterval :
    def __init__(self,interval,action) :
        self.interval=interval
        self.action=action
        self.stopEvent=threading.Event()
        thread=threading.Thread(target=self.__setInterval)
        thread.start()

    def __setInterval(self) :
        nextTime=time.time()+self.interval
        while not self.stopEvent.wait(nextTime-time.time()) :
            nextTime+=self.interval
            self.action()

    def cancel(self) :
        self.stopEvent.set()

# start action every 0.6s
inter=setInterval(0.6,action)
print('just after setInterval -> time : {:.1f}s'.format(time.time()-StartTime))

# will stop interval in 5s
t=threading.Timer(5,inter.cancel)
t.start()
1

Đã trả lời ngày 10 tháng 12 năm 2019 lúc 14:46Dec 10, 2019 at 14:46

Hướng dẫn how to set time interval in python - cách đặt khoảng thời gian trong python

Pavan Varyanipavan VaryaniPavan Varyani

1.3241 huy hiệu vàng6 Huy hiệu bạc15 Huy hiệu đồng1 gold badge6 silver badges15 bronze badges

SetInterVal nên được chạy trên nhiều luồng và không đóng băng tác vụ khi nó chạy vòng.

Dưới đây là gói thời gian chạy của tôi hỗ trợ tính năng đa luồng:

  • SetTimeout (F, MS): TiMMing To Fire Chức năng trong luồng độc lập. : timming to fire function in independence thread.
  • Delayf (F, MS): SetTimeout tương tự (F, MS).
  • setInterval (f, ms): vòng lặp không đồng bộ .pause, .resume: tạm dừng và tiếp tục khoảng thời gian : asynchronous loop .pause, .resume : pause and resume the interval
  • ClearInterval (khoảng thời gian): Xóa khoảng thời gian : clear the interval

Nó ngắn và đơn giản. Lưu ý rằng Python cần Lambda nếu bạn nhập hàm trực tiếp, nhưng Lambda không phải là khối lệnh hỗ trợ, vì vậy bạn nên xác định nội dung chức năng trước khi đặt nó vào setInterval.

import time, threading

StartTime=time.time()

def action() :
    print('action ! -> time : {:.1f}s'.format(time.time()-StartTime))


class setInterval :
    def __init__(self,interval,action) :
        self.interval=interval
        self.action=action
        self.stopEvent=threading.Event()
        thread=threading.Thread(target=self.__setInterval)
        thread.start()

    def __setInterval(self) :
        nextTime=time.time()+self.interval
        while not self.stopEvent.wait(nextTime-time.time()) :
            nextTime+=self.interval
            self.action()

    def cancel(self) :
        self.stopEvent.set()

# start action every 0.6s
inter=setInterval(0.6,action)
print('just after setInterval -> time : {:.1f}s'.format(time.time()-StartTime))

# will stop interval in 5s
t=threading.Timer(5,inter.cancel)
t.start()
2

Lưu vào File .Py và chạy nó. Bạn sẽ thấy nó in cả số ngẫu nhiên và chuỗi "AAAAA". Chủ đề số in sẽ tạm dừng in sau 1 giây và tiếp tục in lại trong 1 giây sau đó dừng lại, trong khi chuỗi in tiếp tục in văn bản không bị hỏng.

Trong trường hợp bạn sử dụng OpenCV cho hoạt hình đồ họa với các setinterval để tăng tốc độ animate, bạn phải có 1 luồng chính để áp dụng Waitkey, nếu không cửa sổ sẽ đóng băng cho dù bạn có bị chậm hay bạn áp dụng Waitkey trong luồng phụ: for graphic animation with those setInterval for boost animate speed, you must have 1 main thread to apply waitKey, otherwise the window will freeze no matter how slow delay or you applied waitKey in sub thread:

import time, threading

StartTime=time.time()

def action() :
    print('action ! -> time : {:.1f}s'.format(time.time()-StartTime))


class setInterval :
    def __init__(self,interval,action) :
        self.interval=interval
        self.action=action
        self.stopEvent=threading.Event()
        thread=threading.Thread(target=self.__setInterval)
        thread.start()

    def __setInterval(self) :
        nextTime=time.time()+self.interval
        while not self.stopEvent.wait(nextTime-time.time()) :
            nextTime+=self.interval
            self.action()

    def cancel(self) :
        self.stopEvent.set()

# start action every 0.6s
inter=setInterval(0.6,action)
print('just after setInterval -> time : {:.1f}s'.format(time.time()-StartTime))

# will stop interval in 5s
t=threading.Timer(5,inter.cancel)
t.start()
3

Đã trả lời ngày 22 tháng 12 năm 2021 lúc 4:17Dec 22, 2021 at 4:17

Hướng dẫn how to set time interval in python - cách đặt khoảng thời gian trong python

Phghuepenghuephnghue

1.4662 huy hiệu vàng10 Huy hiệu bạc9 Huy hiệu đồng2 gold badges10 silver badges9 bronze badges

1

Bạn cũng có thể thử phương pháp này:

import time, threading

StartTime=time.time()

def action() :
    print('action ! -> time : {:.1f}s'.format(time.time()-StartTime))


class setInterval :
    def __init__(self,interval,action) :
        self.interval=interval
        self.action=action
        self.stopEvent=threading.Event()
        thread=threading.Thread(target=self.__setInterval)
        thread.start()

    def __setInterval(self) :
        nextTime=time.time()+self.interval
        while not self.stopEvent.wait(nextTime-time.time()) :
            nextTime+=self.interval
            self.action()

    def cancel(self) :
        self.stopEvent.set()

# start action every 0.6s
inter=setInterval(0.6,action)
print('just after setInterval -> time : {:.1f}s'.format(time.time()-StartTime))

# will stop interval in 5s
t=threading.Timer(5,inter.cancel)
t.start()
4

Vì vậy, nó sẽ in "5 giây đã trôi qua" cứ sau 5 giây.

Hàm

just after setInterval -> time : 0.0s
action ! -> time : 0.6s
action ! -> time : 1.2s
action ! -> time : 1.8s
action ! -> time : 2.4s
action ! -> time : 3.0s
action ! -> time : 3.6s
action ! -> time : 4.2s
action ! -> time : 4.8s
7 đình chỉ thực thi trong số giây đã cho. Đối số có thể là một số điểm nổi để chỉ ra thời gian ngủ chính xác hơn.

Tomerikoo

16.8K15 Huy hiệu vàng39 Huy hiệu bạc57 Huy hiệu đồng15 gold badges39 silver badges57 bronze badges

Đã trả lời ngày 13 tháng 10 năm 2021 lúc 7:04Oct 13, 2021 at 7:04

LIBANLIBANLiban

1011 Huy hiệu bạc2 Huy hiệu đồng1 silver badge2 bronze badges

Gần đây, tôi có cùng một vấn đề với bạn. Và tôi thấy những điều này:

1. Bạn có thể sử dụng thư viện: Threading.time (Điều này có phần giới thiệu ở trên)

2. Bạn có thể sử dụng thư viện: Lịch (điều này cũng có phần giới thiệu ở trên)

3. Bạn có thể sử dụng thư viện: Bộ lập lịch Python nâng cao (Đề xuất)(Recommend)

Đã trả lời ngày 18 tháng 3 năm 2014 lúc 1:19Mar 18, 2014 at 1:19

NI Xiaonini XiaoniNi Xiaoni

1.5992 Huy hiệu vàng12 Huy hiệu bạc10 Huy hiệu đồng2 gold badges12 silver badges10 bronze badges

Một số câu trả lời ở trên sử dụng

just after setInterval -> time : 0.0s
action ! -> time : 0.6s
action ! -> time : 1.2s
action ! -> time : 1.8s
action ! -> time : 2.4s
action ! -> time : 3.0s
action ! -> time : 3.6s
action ! -> time : 4.2s
action ! -> time : 4.8s
8 và
just after setInterval -> time : 0.0s
action ! -> time : 0.6s
action ! -> time : 1.2s
action ! -> time : 1.8s
action ! -> time : 2.4s
action ! -> time : 3.0s
action ! -> time : 3.6s
action ! -> time : 4.2s
action ! -> time : 4.8s
5 thực sự hoạt động, ngoại trừ việc nó sinh ra một luồng mới mỗi khi một khoảng thời gian được gọi, điều này gây ra các vấn đề về bộ nhớ.

Ví dụ cơ bản dưới đây thực hiện một cách gần như cơ chế tương tự bằng cách đặt khoảng vào một luồng riêng biệt. Nó ngủ trong khoảng thời gian đã cho. Trước khi nhảy vào mã, đây là một số hạn chế mà bạn cần biết:roughly implemented a similar mechanism by putting interval on a separate thread. It sleeps at the given interval. Before jumping into code, here are some of the limitations that you need to be aware of:

  1. JavaScript là một luồng đơn, vì vậy khi chức năng bên trong

    just after setInterval -> time : 0.0s
    action ! -> time : 0.6s
    action ! -> time : 1.2s
    action ! -> time : 1.8s
    action ! -> time : 2.4s
    action ! -> time : 3.0s
    action ! -> time : 3.6s
    action ! -> time : 4.2s
    action ! -> time : 4.8s
    
    6 được bắn, không có gì khác sẽ hoạt động cùng một lúc (không bao gồm chủ đề công nhân, nhưng hãy nói về trường hợp sử dụng chung của
    just after setInterval -> time : 0.0s
    action ! -> time : 0.6s
    action ! -> time : 1.2s
    action ! -> time : 1.8s
    action ! -> time : 2.4s
    action ! -> time : 3.0s
    action ! -> time : 3.6s
    action ! -> time : 4.2s
    action ! -> time : 4.8s
    
    6. có thể gặp phải điều kiện chủng tộc trừ khi sử dụng
    import threading
    
    def setInterval(func,time):
        e = threading.Event()
        while not e.wait(time):
            func()
    
    def foo():
        print "hello"
    
    # using
    setInterval(foo,5)
    
    # output:
    hello
    hello
    .
    .
    .
    
    2.

  2. Việc triển khai dưới đây sử dụng

    import threading
    
    def setInterval(func,time):
        e = threading.Event()
        while not e.wait(time):
            func()
    
    def foo():
        print "hello"
    
    # using
    setInterval(foo,5)
    
    # output:
    hello
    hello
    .
    .
    .
    
    3 để mô phỏng các khoảng thời gian, nhưng thêm thời gian thực hiện là
    import threading
    
    def setInterval(func,time):
        e = threading.Event()
        while not e.wait(time):
            func()
    
    def foo():
        print "hello"
    
    # using
    setInterval(foo,5)
    
    # output:
    hello
    hello
    .
    .
    .
    
    4, tổng thời gian cho khoảng thời gian này có thể lớn hơn những gì bạn mong đợi. Vì vậy, tùy thuộc vào các trường hợp sử dụng, bạn có thể muốn "ngủ ít hơn" (trừ thời gian để gọi
    import threading
    
    def setInterval(func,time):
        e = threading.Event()
        while not e.wait(time):
            func()
    
    def foo():
        print "hello"
    
    # using
    setInterval(foo,5)
    
    # output:
    hello
    hello
    .
    .
    .
    
    4)interval may be greater than what you expect. So depending on use cases, you may want to "sleep less" (minus time taken for calling
    import threading
    
    def setInterval(func,time):
        e = threading.Event()
        while not e.wait(time):
            func()
    
    def foo():
        print "hello"
    
    # using
    setInterval(foo,5)
    
    # output:
    hello
    hello
    .
    .
    .
    
    4)

  3. Tôi chỉ thử nghiệm điều này và bạn chắc chắn không nên sử dụng các biến toàn cầu theo cách tôi đã làm, hãy thoải mái điều chỉnh nó để nó phù hợp với hệ thống của bạn.roughly tested this, and you should definitely not use global variables the way I did, feel free to tweak it so that it fits in your system.


Nói đủ, đây là mã:

import time, threading

StartTime=time.time()

def action() :
    print('action ! -> time : {:.1f}s'.format(time.time()-StartTime))


class setInterval :
    def __init__(self,interval,action) :
        self.interval=interval
        self.action=action
        self.stopEvent=threading.Event()
        thread=threading.Thread(target=self.__setInterval)
        thread.start()

    def __setInterval(self) :
        nextTime=time.time()+self.interval
        while not self.stopEvent.wait(nextTime-time.time()) :
            nextTime+=self.interval
            self.action()

    def cancel(self) :
        self.stopEvent.set()

# start action every 0.6s
inter=setInterval(0.6,action)
print('just after setInterval -> time : {:.1f}s'.format(time.time()-StartTime))

# will stop interval in 5s
t=threading.Timer(5,inter.cancel)
t.start()
5

Đầu ra dự kiến:

import time, threading

StartTime=time.time()

def action() :
    print('action ! -> time : {:.1f}s'.format(time.time()-StartTime))


class setInterval :
    def __init__(self,interval,action) :
        self.interval=interval
        self.action=action
        self.stopEvent=threading.Event()
        thread=threading.Thread(target=self.__setInterval)
        thread.start()

    def __setInterval(self) :
        nextTime=time.time()+self.interval
        while not self.stopEvent.wait(nextTime-time.time()) :
            nextTime+=self.interval
            self.action()

    def cancel(self) :
        self.stopEvent.set()

# start action every 0.6s
inter=setInterval(0.6,action)
print('just after setInterval -> time : {:.1f}s'.format(time.time()-StartTime))

# will stop interval in 5s
t=threading.Timer(5,inter.cancel)
t.start()
6

Đã trả lời ngày 23 tháng 6 năm 2017 lúc 17:11Jun 23, 2017 at 17:11

Hướng dẫn how to set time interval in python - cách đặt khoảng thời gian trong python

Benjaminzbenjaminzbenjaminz

2.9583 huy hiệu vàng33 Huy hiệu bạc47 Huy hiệu đồng3 gold badges33 silver badges47 bronze badges

Mô -đun Python 3 của tôi

import threading

def setInterval(func,time):
    e = threading.Event()
    while not e.wait(time):
        func()

def foo():
    print "hello"

# using
setInterval(foo,5)

# output:
hello
hello
.
.
.
6 sẽ hữu ích! Đây là:

import time, threading

StartTime=time.time()

def action() :
    print('action ! -> time : {:.1f}s'.format(time.time()-StartTime))


class setInterval :
    def __init__(self,interval,action) :
        self.interval=interval
        self.action=action
        self.stopEvent=threading.Event()
        thread=threading.Thread(target=self.__setInterval)
        thread.start()

    def __setInterval(self) :
        nextTime=time.time()+self.interval
        while not self.stopEvent.wait(nextTime-time.time()) :
            nextTime+=self.interval
            self.action()

    def cancel(self) :
        self.stopEvent.set()

# start action every 0.6s
inter=setInterval(0.6,action)
print('just after setInterval -> time : {:.1f}s'.format(time.time()-StartTime))

# will stop interval in 5s
t=threading.Timer(5,inter.cancel)
t.start()
7

Mã chỉnh sửa: Đã sửa lỗi rò rỉ bộ nhớ (được phát hiện bởi @benjaminz). Bây giờ tất cả các chủ đề được làm sạch vào cuối. Tại sao rò rỉ này xảy ra? Nó xảy ra vì các tài liệu tham khảo ngầm (hoặc thậm chí rõ ràng). Trong trường hợp của tôi,

import threading

def setInterval(func,time):
    e = threading.Event()
    while not e.wait(time):
        func()

def foo():
    print "hello"

# using
setInterval(foo,5)

# output:
hello
hello
.
.
.
7 và
import threading

def setInterval(func,time):
    e = threading.Event()
    while not e.wait(time):
        func()

def foo():
    print "hello"

# using
setInterval(foo,5)

# output:
hello
hello
.
.
.
8. Thời gian chờ tự động tự động (sau bản vá này) vì họ sử dụng trình bao bọc chức năng gọi hàm và sau đó tự tạo ra. Nhưng làm thế nào điều này xảy ra? Các đối tượng không thể bị xóa khỏi bộ nhớ trừ khi tất cả các tài liệu tham khảo cũng bị xóa hoặc mô -đun
import threading

def setInterval(func,time):
    e = threading.Event()
    while not e.wait(time):
        func()

def foo():
    print "hello"

# using
setInterval(foo,5)

# output:
hello
hello
.
.
.
9 được sử dụng. Giải thích: Không có cách nào để tạo (trong mã của tôi) các tài liệu tham khảo không mong muốn về thời gian chờ/khoảng thời gian. Họ chỉ có một người giới thiệu: ________ 37/________ 38. Và, khi bị gián đoạn hoặc kết thúc (chỉ có thời gian chờ có thể hoàn thành không bị gián đoạn), họ xóa tham chiếu duy nhất hiện có cho chính họ: phần tử dict tương ứng của chúng. Các lớp được đóng gói hoàn hảo bằng cách sử dụng
import threading

class ThreadJob(threading.Thread):
    def __init__(self,callback,event,interval):
        '''runs the callback function after interval seconds

        :param callback:  callback function to invoke
        :param event: external event for controlling the update operation
        :param interval: time in seconds after which are required to fire the callback
        :type callback: function
        :type interval: int
        '''
        self.callback = callback
        self.event = event
        self.interval = interval
        super(ThreadJob,self).__init__()

    def run(self):
        while not self.event.wait(self.interval):
            self.callback()



event = threading.Event()

def foo():
    print "hello"

k = ThreadJob(foo,event,2)
k.start()

print "It is non-blocking"
2, vì vậy không có dung lượng để rò rỉ bộ nhớ.
Fixed the memory leak (spotted by @benjaminz). Now ALL threads are cleaned up upon end. Why does this leak happen? It happens because of the implicit (or even explicit) references. In my case,
import threading

def setInterval(func,time):
    e = threading.Event()
    while not e.wait(time):
        func()

def foo():
    print "hello"

# using
setInterval(foo,5)

# output:
hello
hello
.
.
.
7 and
import threading

def setInterval(func,time):
    e = threading.Event()
    while not e.wait(time):
        func()

def foo():
    print "hello"

# using
setInterval(foo,5)

# output:
hello
hello
.
.
.
8. Timeouts self-clean automatically (after this patch) because they use function wrapper which calls the function and then self-kills. But how does this happen? Objects can't be deleted from memory unless all references are deleted too or
import threading

def setInterval(func,time):
    e = threading.Event()
    while not e.wait(time):
        func()

def foo():
    print "hello"

# using
setInterval(foo,5)

# output:
hello
hello
.
.
.
9 module is used. Explaining: there's no way to create (in my code) unwanted references to timeouts/intervals. They have only ONE referrer: the
import threading

def setInterval(func,time):
    e = threading.Event()
    while not e.wait(time):
        func()

def foo():
    print "hello"

# using
setInterval(foo,5)

# output:
hello
hello
.
.
.
7/
import threading

def setInterval(func,time):
    e = threading.Event()
    while not e.wait(time):
        func()

def foo():
    print "hello"

# using
setInterval(foo,5)

# output:
hello
hello
.
.
.
8 dicts. And, when interrupted or finished (only timeouts can finish uninterrupted) they delete the only existing reference to themselves: their corresponding dict element. Classes are perfectly encapsulated using
import threading

class ThreadJob(threading.Thread):
    def __init__(self,callback,event,interval):
        '''runs the callback function after interval seconds

        :param callback:  callback function to invoke
        :param event: external event for controlling the update operation
        :param interval: time in seconds after which are required to fire the callback
        :type callback: function
        :type interval: int
        '''
        self.callback = callback
        self.event = event
        self.interval = interval
        super(ThreadJob,self).__init__()

    def run(self):
        while not self.event.wait(self.interval):
            self.callback()



event = threading.Event()

def foo():
    print "hello"

k = ThreadJob(foo,event,2)
k.start()

print "It is non-blocking"
2, so no space for memory leaks.

Đã trả lời ngày 16 tháng 7 năm 2017 lúc 10:27Jul 16, 2017 at 10:27

KotauskaskotauskasKotauskas

1.14710 Huy hiệu bạc 30 Huy hiệu Đồng10 silver badges30 bronze badges

Dưới đây là một giải pháp trôi dạt thời gian thấp sử dụng một luồng để định kỳ báo hiệu một đối tượng sự kiện. Các chuỗi chạy () hầu như không có gì trong khi chờ đợi thời gian chờ; Do đó thời gian thấp trôi.

import time, threading

StartTime=time.time()

def action() :
    print('action ! -> time : {:.1f}s'.format(time.time()-StartTime))


class setInterval :
    def __init__(self,interval,action) :
        self.interval=interval
        self.action=action
        self.stopEvent=threading.Event()
        thread=threading.Thread(target=self.__setInterval)
        thread.start()

    def __setInterval(self) :
        nextTime=time.time()+self.interval
        while not self.stopEvent.wait(nextTime-time.time()) :
            nextTime+=self.interval
            self.action()

    def cancel(self) :
        self.stopEvent.set()

# start action every 0.6s
inter=setInterval(0.6,action)
print('just after setInterval -> time : {:.1f}s'.format(time.time()-StartTime))

# will stop interval in 5s
t=threading.Timer(5,inter.cancel)
t.start()
8

Đã trả lời ngày 20 tháng 11 năm 2017 lúc 19:13Nov 20, 2017 at 19:13

Bobwirkabobwirkabobwirka

3141 Huy hiệu vàng6 Huy hiệu bạc1 gold badge6 silver badges10 bronze badges

Ngủ vào khoảng thời gian tiếp theo của độ dài

import threading

class ThreadJob(threading.Thread):
    def __init__(self,callback,event,interval):
        '''runs the callback function after interval seconds

        :param callback:  callback function to invoke
        :param event: external event for controlling the update operation
        :param interval: time in seconds after which are required to fire the callback
        :type callback: function
        :type interval: int
        '''
        self.callback = callback
        self.event = event
        self.interval = interval
        super(ThreadJob,self).__init__()

    def run(self):
        while not self.event.wait(self.interval):
            self.callback()



event = threading.Event()

def foo():
    print "hello"

k = ThreadJob(foo,event,2)
k.start()

print "It is non-blocking"
3 bắt đầu: (không đồng thời)

import time, threading

StartTime=time.time()

def action() :
    print('action ! -> time : {:.1f}s'.format(time.time()-StartTime))


class setInterval :
    def __init__(self,interval,action) :
        self.interval=interval
        self.action=action
        self.stopEvent=threading.Event()
        thread=threading.Thread(target=self.__setInterval)
        thread.start()

    def __setInterval(self) :
        nextTime=time.time()+self.interval
        while not self.stopEvent.wait(nextTime-time.time()) :
            nextTime+=self.interval
            self.action()

    def cancel(self) :
        self.stopEvent.set()

# start action every 0.6s
inter=setInterval(0.6,action)
print('just after setInterval -> time : {:.1f}s'.format(time.time()-StartTime))

# will stop interval in 5s
t=threading.Timer(5,inter.cancel)
t.start()
9

Đơn giản và không trôi dạt.

Đã trả lời ngày 15 tháng 4 năm 2020 lúc 12:51Apr 15, 2020 at 12:51

qrtlsqrtlsqrtLs

1.82622 huy hiệu bạc42 huy hiệu đồng22 silver badges42 bronze badges

Tôi đã viết mã của mình để tạo ra một setinterval rất linh hoạt trong Python. Của bạn đây:

just after setInterval -> time : 0.0s
action ! -> time : 0.6s
action ! -> time : 1.2s
action ! -> time : 1.8s
action ! -> time : 2.4s
action ! -> time : 3.0s
action ! -> time : 3.6s
action ! -> time : 4.2s
action ! -> time : 4.8s
0

Bạn có thể có được nhiều tính năng và tính linh hoạt. Chạy mã này sẽ không đóng băng mã của bạn, bạn có thể thay đổi khoảng thời gian trong thời gian chạy, bạn có thể thay đổi hàm trong thời gian chạy, bạn có thể chuyển các đối số, bạn có thể nhận đối tượng được trả về từ chức năng của mình và nhiều hơn nữa. Bạn cũng có thể thực hiện thủ thuật của mình!

Đây là một ví dụ rất đơn giản và cơ bản để sử dụng nó:

just after setInterval -> time : 0.0s
action ! -> time : 0.6s
action ! -> time : 1.2s
action ! -> time : 1.8s
action ! -> time : 2.4s
action ! -> time : 3.0s
action ! -> time : 3.6s
action ! -> time : 4.2s
action ! -> time : 4.8s
1

Kiểm tra dự án GitHub của tôi để xem thêm các ví dụ và theo dõi các bản cập nhật tiếp theo: d https://github.com/hzzkygcs/setinterval-python

Đã trả lời ngày 25 tháng 3 năm 2020 lúc 15:50Mar 25, 2020 at 15:50

Hướng dẫn how to set time interval in python - cách đặt khoảng thời gian trong python

HzzKYGCSHZZKYGCSHzzkygcs

1.2301 Huy hiệu vàng16 Huy hiệu bạc23 Huy hiệu đồng1 gold badge16 silver badges23 bronze badges

Mọi thứ hoạt động khác nhau trong Python: bạn cần phải

just after setInterval -> time : 0.0s
action ! -> time : 0.6s
action ! -> time : 1.2s
action ! -> time : 1.8s
action ! -> time : 2.4s
action ! -> time : 3.0s
action ! -> time : 3.6s
action ! -> time : 4.2s
action ! -> time : 4.8s
7 (nếu bạn muốn chặn luồng hiện tại) hoặc bắt đầu một luồng mới. Xem http://docs.python.org/l Library/threading.html

Đã trả lời ngày 23 tháng 4 năm 2010 lúc 8:04Apr 23, 2010 at 8:04

EmpempEMP

57K52 Huy hiệu vàng163 Huy hiệu bạc220 Huy hiệu đồng52 gold badges163 silver badges220 bronze badges

1

Đây là một cái gì đó dễ dàng Peazy:

just after setInterval -> time : 0.0s
action ! -> time : 0.6s
action ! -> time : 1.2s
action ! -> time : 1.8s
action ! -> time : 2.4s
action ! -> time : 3.0s
action ! -> time : 3.6s
action ! -> time : 4.2s
action ! -> time : 4.8s
2

Đã trả lời ngày 9 tháng 11 năm 2020 lúc 10:30Nov 9, 2020 at 10:30

Trishant Pahwatrishant PahwaTrishant Pahwa

2.1521 Huy hiệu vàng11 Huy hiệu bạc29 Huy hiệu đồng1 gold badge11 silver badges29 bronze badges

5

Từ tài liệu Python:

just after setInterval -> time : 0.0s
action ! -> time : 0.6s
action ! -> time : 1.2s
action ! -> time : 1.8s
action ! -> time : 2.4s
action ! -> time : 3.0s
action ! -> time : 3.6s
action ! -> time : 4.2s
action ! -> time : 4.8s
3

Đã trả lời ngày 23 tháng 4 năm 2010 lúc 8:07Apr 23, 2010 at 8:07

nkrkvnkrkvnkrkv

6.9744 Huy hiệu vàng27 Huy hiệu bạc36 Huy hiệu đồng4 gold badges27 silver badges36 bronze badges

6