복붙노트

[PYTHON] 파이썬은 setInterval ()과 동등한가요?

PYTHON

파이썬은 setInterval ()과 동등한가요?

파이썬에는 JavaScript의 setInterval ()과 비슷한 기능이 있습니까?

감사

해결법

  1. ==============================

    1.이것은 당신이 찾고 있던 올바른 스 니펫 일 수 있습니다 :

    이것은 당신이 찾고 있던 올바른 스 니펫 일 수 있습니다 :

    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
    
  2. ==============================

    2.간단하고 멋지게 유지하십시오. 왜 모든 대답이 복잡한 것을 너무 복잡하게 만드는지 모르겠습니다.

    간단하고 멋지게 유지하십시오. 왜 모든 대답이 복잡한 것을 너무 복잡하게 만드는지 모르겠습니다.

    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
    .
    .
    .
    

    편집 :이 코드는 비 블로킹입니다.

    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. ==============================

    3.sched 모듈은 일반적인 파이썬 코드에 이러한 능력을 제공합니다. 그러나 문서에서 알 수 있듯이 코드가 다중 스레드 인 경우 threading.Timer 클래스를 대신 사용하는 것이 좋습니다.

    sched 모듈은 일반적인 파이썬 코드에 이러한 능력을 제공합니다. 그러나 문서에서 알 수 있듯이 코드가 다중 스레드 인 경우 threading.Timer 클래스를 대신 사용하는 것이 좋습니다.

  4. ==============================

    4.Nailxx의 대답을 조금 바꾸면 답을 얻을 수 있습니다!

    Nailxx의 대답을 조금 바꾸면 답을 얻을 수 있습니다!

    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
    
  5. ==============================

    5.나는 이것이 당신이 한 일이라고 생각합니다.

    나는 이것이 당신이 한 일이라고 생각합니다.

    #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()
    

    반복 메소드가 끝날 때 스케줄러에 다른 항목을 추가하면 계속 진행됩니다.

  6. ==============================

    6.이것은 시작하고 중지 할 수있는 버전입니다. 그것은 차단되지 않습니다. 실행 시간 오류가 추가되지 않으므로 결함이 없습니다 (예 : 오디오와 같이 매우 짧은 간격으로 장시간 실행하는 경우 중요 함)

    이것은 시작하고 중지 할 수있는 버전입니다. 그것은 차단되지 않습니다. 실행 시간 오류가 추가되지 않으므로 결함이 없습니다 (예 : 오디오와 같이 매우 짧은 간격으로 장시간 실행하는 경우 중요 함)

    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()
    

    출력은 다음과 같습니다.

    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. ==============================

    7.최근에, 나는 당신과 같은 문제가 있습니다. 그리고 나는이 해결책을 찾는다.

    최근에, 나는 당신과 같은 문제가 있습니다. 그리고 나는이 해결책을 찾는다.

    1. 당신은 라이브러리를 사용할 수 있습니다 : threading.Time (위의 소개가 있습니다)

    2. 라이브러리를 사용할 수 있습니다 : sched (이것 역시 위의 소개가 있습니다)

    3. 라이브러리를 사용할 수 있습니다 : 고급 Python 스케줄러 (권장)

  8. ==============================

    8.위의 방법은 간격을 취소 할 수 있어야하기 때문에 나에게 그다지 도움이되지 않았습니다. 이 함수를 클래스로 바꾸고 다음을 생각해 냈습니다.

    위의 방법은 간격을 취소 할 수 있어야하기 때문에 나에게 그다지 도움이되지 않았습니다. 이 함수를 클래스로 바꾸고 다음을 생각해 냈습니다.

    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()
    
  9. ==============================

    9.위의 몇 가지 대답은 func_wrapper와 threading.Timer를 사용합니다. 단, 간격이 호출 될 때마다 새 스레드가 생성되어 메모리 문제가 발생합니다.

    위의 몇 가지 대답은 func_wrapper와 threading.Timer를 사용합니다. 단, 간격이 호출 될 때마다 새 스레드가 생성되어 메모리 문제가 발생합니다.

    아래의 기본 예제는 대략 별도의 스레드에 간격을 두어 유사한 메커니즘을 구현했습니다. 주어진 간격으로 잔다. 코드로 들어가기 전에 알아 두어야 할 몇 가지 제한 사항은 다음과 같습니다.

    이야기가 충분합니다. 코드는 다음과 같습니다.

    # Python 2.7
    import threading
    import time
    
    
    class Interval(object):
        def __init__(self):
            self.daemon_alive = True
            self.thread = None # keep a reference to the thread so that we can "join"
    
        def ticktock(self, interval, func):
            while self.daemon_alive:
                time.sleep(interval)
                func()
    
    num = 0
    def print_num():
        global num
        num += 1
        print 'num + 1 = ', num
    
    def print_negative_num():
        global num
        print '-num = ', num * -1
    
    intervals = {} # keep track of intervals
    g_id_counter = 0 # roughly generate ids for intervals
    
    def set_interval(interval, func):
        global g_id_counter
    
        interval_obj = Interval()
        # Put this interval on a new thread
        t = threading.Thread(target=interval_obj.ticktock, args=(interval, func))
        t.setDaemon(True)
        interval_obj.thread = t
        t.start()
    
        # Register this interval so that we can clear it later
        # using roughly generated id
        interval_id = g_id_counter
        g_id_counter += 1
        intervals[interval_id] = interval_obj
    
        # return interval id like it does in JavaScript
        return interval_id
    
    def clear_interval(interval_id):
        # terminate this interval's while loop
        intervals[interval_id].daemon_alive = False
        # kill the thread
        intervals[interval_id].thread.join()
        # pop out the interval from registry for reusing
        intervals.pop(interval_id)
    
    if __name__ == '__main__':
        num_interval = set_interval(1, print_num)
        neg_interval = set_interval(3, print_negative_num)
    
        time.sleep(10) # Sleep 10 seconds on main thread to let interval run
        clear_interval(num_interval)
        clear_interval(neg_interval)
        print "- Are intervals all cleared?"
        time.sleep(3) # check if both intervals are stopped (not printing)
        print "- Yup, time to get beers"
    

    예상 출력 :

    num + 1 =  1
    num + 1 =  2
    -num =  -2
     num + 1 =  3
    num + 1 =  4
    num + 1 =  5
    -num =  -5
    num + 1 =  6
    num + 1 =  7
    num + 1 =  8
    -num =  -8
    num + 1 =  9
    num + 1 =  10
    -num =  -10
    Are intervals all cleared?
    Yup, time to get beers
    
  10. ==============================

    10.내 Python 3 모듈 jsinterval.py가 도움이 될 것입니다! 여기있어:

    내 Python 3 모듈 jsinterval.py가 도움이 될 것입니다! 여기있어:

    """
    Threaded intervals and timeouts from JavaScript
    """
    
    import threading, sys
    
    __all__ =  ['TIMEOUTS', 'INTERVALS', 'setInterval', 'clearInterval', 'setTimeout', 'clearTimeout']
    
    TIMEOUTS  = {}
    INTERVALS = {}
    
    last_timeout_id  = 0
    last_interval_id = 0
    
    class Timeout:
        """Class for all timeouts."""
        def __init__(self, func, timeout):
            global last_timeout_id
            last_timeout_id += 1
            self.timeout_id = last_timeout_id
            TIMEOUTS[str(self.timeout_id)] = self
            self.func = func
            self.timeout = timeout
            self.threadname = 'Timeout #%s' %self.timeout_id
    
        def run(self):
            func = self.func
            delx = self.__del__
            def func_wrapper():
                func()
                delx()
            self.t = threading.Timer(self.timeout/1000, func_wrapper)
            self.t.name = self.threadname
            self.t.start()
    
        def __repr__(self):
            return '<JS Timeout set for %s seconds, launching function %s on timeout reached>' %(self.timeout, repr(self.func))
    
        def __del__(self):
            self.t.cancel()
    
    class Interval:
        """Class for all intervals."""
        def __init__(self, func, interval):
            global last_interval_id
            self.interval_id = last_interval_id
            INTERVALS[str(self.interval_id)] = self
            last_interval_id += 1
            self.func = func
            self.interval = interval
            self.threadname = 'Interval #%s' %self.interval_id
    
        def run(self):
            func = self.func
            interval = self.interval
            def func_wrapper():
                timeout = Timeout(func_wrapper, interval)
                self.timeout = timeout
                timeout.run()
                func()
            self.t = threading.Timer(self.interval/1000, func_wrapper)
            self.t.name = self.threadname
            self.t.run()
    
        def __repr__(self):
            return '<JS Interval, repeating function %s with interval %s>' %(repr(self.func), self.interval)
    
        def __del__(self):
            self.timeout.__del__()
    
    def setInterval(func, interval):
        """
        Create a JS Interval: func is the function to repeat, interval is the interval (in ms)
        of executing the function.
        """
        temp = Interval(func, interval)
        temp.run()
        idx = int(temp.interval_id)
        del temp
        return idx
    
    
    def clearInterval(interval_id):
        try:
            INTERVALS[str(interval_id)].__del__()
            del INTERVALS[str(interval_id)]
        except KeyError:
            sys.stderr.write('No such interval "Interval #%s"\n' %interval_id)
    
    def setTimeout(func, timeout):
        """
        Create a JS Timeout: func is the function to timeout, timeout is the timeout (in ms)
        of executing the function.
        """
        temp = Timeout(func, timeout)
        temp.run()
        idx = int(temp.timeout_id)
        del temp
        return idx
    
    
    def clearTimeout(timeout_id):
        try:
            TIMEOUTS[str(timeout_id)].__del__()
            del TIMEOUTS[str(timeout_id)]
        except KeyError:
            sys.stderr.write('No such timeout "Timeout #%s"\n' %timeout_id)
    

    코드 편집 : 메모리 누수가 수정되었습니다 (@benjaminz에서 발견됨). 이제 모든 스레드는 끝날 때 정리됩니다. 왜이 누수가 발생합니까? 암시 적 (또는 명시 적) 참조 때문에 발생합니다. 내 경우, 시간과 간격. 타임 아웃은 자동적으로 (이 패치 이후) 함수를 호출하고 스스로 죽이는 함수 래퍼를 사용하기 때문에 자동으로 정리됩니다. 그러나 어떻게 이런 일이 발생합니까? 모든 참조가 삭제되거나 gc 모듈이 사용되지 않으면 개체를 메모리에서 삭제할 수 없습니다. 설명 : 타임 아웃 / 간격에 대한 원치 않는 참조를 (내 코드에서) 작성할 수있는 방법이 없습니다. TIMEOUTS / INTERVALS에는 하나의 참조 자만 있습니다. 그리고 인터럽트되거나 완료되면 (타임 아웃만이 중단되지 않고 끝날 수있다), 그들 자신에 대한 유일하게 존재하는 참조, 즉 해당 dict 요소를 삭제한다. 클래스는 __all__을 사용하여 완벽하게 캡슐화되므로 메모리 누수가 발생하지 않습니다.

  11. ==============================

    11.스레드를 사용하여 Event 객체에 주기적으로 신호를 보내는 낮은 시간 드리프트 솔루션이 있습니다. 스레드의 run ()은 시간 초과를 기다리는 동안 거의 아무 것도하지 않습니다. 그러므로 낮은 시간 표류.

    스레드를 사용하여 Event 객체에 주기적으로 신호를 보내는 낮은 시간 드리프트 솔루션이 있습니다. 스레드의 run ()은 시간 초과를 기다리는 동안 거의 아무 것도하지 않습니다. 그러므로 낮은 시간 표류.

    # Example of low drift (time) periodic execution of a function.
    import threading
    import time
    
    # Thread that sets 'flag' after 'timeout'
    class timerThread (threading.Thread):
    
        def __init__(self , timeout , flag):
            threading.Thread.__init__(self)
            self.timeout = timeout
            self.stopFlag = False
            self.event = threading.Event()
            self.flag = flag
    
        # Low drift run(); there is only the 'if'
        # and 'set' methods between waits.
        def run(self):
            while not self.event.wait(self.timeout):
                if self.stopFlag:
                    break
                self.flag.set()
    
        def stop(self):
            stopFlag = True
            self.event.set()
    
    # Data.
    printCnt = 0
    
    # Flag to print.
    printFlag = threading.Event()
    
    # Create and start the timer thread.
    printThread = timerThread(3 , printFlag)
    printThread.start()
    
    # Loop to wait for flag and print time.
    while True:
    
        global printCnt
    
        # Wait for flag.
        printFlag.wait()
        # Flag must be manually cleared.
        printFlag.clear()
        print(time.time())
        printCnt += 1
        if printCnt == 3:
            break;
    
    # Stop the thread and exit.
    printThread.stop()
    printThread.join()
    print('Done')
    
  12. ==============================

    12.파이썬에서는 상황이 다르게 작동합니다. sleep () (현재 스레드를 차단하려는 경우) 또는 새 스레드를 시작해야합니다. http://docs.python.org/library/threading.html을 참조하십시오.

    파이썬에서는 상황이 다르게 작동합니다. sleep () (현재 스레드를 차단하려는 경우) 또는 새 스레드를 시작해야합니다. http://docs.python.org/library/threading.html을 참조하십시오.

  13. ==============================

    13.파이썬 문서에서 :

    파이썬 문서에서 :

    from threading import Timer
    
    def hello():
        print "hello, world"
    
    t = Timer(30.0, hello)
    t.start() # after 30 seconds, "hello, world" will be printed
    
  14. from https://stackoverflow.com/questions/2697039/python-equivalent-of-setinterval by cc-by-sa and MIT license