Chức năng chạy trong thời gian nhất định python

Cách phổ biến nhất để thực thi một chức năng mỗi x giây trong Python là sử dụng thời gian. phương thức ngủ []. Thời gian. Hàm sleep[] là một hàm có sẵn trong Python được sử dụng để làm cho chương trình ngủ trong thời gian đã chỉ định

Chúng ta có thể sử dụng thời gian. ngủ để thực thi cứ sau x giây. Có hai cách khác nhau để sử dụng thời gian. ngủ[]

Sử dụng thời gian sai cách. ngủ[]

Đoạn mã dưới đây không thực thi cứ sau 60 giây. nó đặt khoảng cách 60 giây giữa các lần thực hiện. Nó chỉ xảy ra sau mỗi 60 giây nếu mã được thực thi của bạn hoàn toàn không mất thời gian

import time
while True:
    # Code executed here
    time.sleep[60]

Cách tốt để sử dụng thời gian. ngủ[]

import time
starttime = time.time[]
while True:
    print["tick"]
    time.sleep[60.0 - [[time.time[] - starttime] % 60.0]]

Phương pháp số 2. Sử dụng mô-đun lập lịch trong Python để thực thi mã Python sau khoảng thời gian.

Chúng ta có thể sử dụng mô-đun lập lịch để gọi hàm hoặc một khối mã python sau một khoảng thời gian bằng cách sử dụng mô-đun lập lịch. Mô-đun lập lịch là một mô-đun python được sử dụng để lên lịch cho mã

import sched, time
s = sched.scheduler[time.time, time.sleep]
def do_something[sc]: 
    print["Doing stuff..."]
    # do your stuff
    sc.enter[60, 1, do_something, [sc,]]

s.enter[60, 1, do_something, [s,]]
s.run[]

Phương pháp số 3. Sử dụng mô-đun apscheduler trong Python để thực thi chức năng cứ sau x giây

Bạn có thể sử dụng mô-đun apscheduler của bên thứ ba này trong python. Nó cũng rất hữu ích theo những cách khác. Bạn có thể cung cấp các chức năng khác như blockscheduler, TwistedScheduler và nhiều chức năng khác

from apscheduler.schedulers.background import BlockingScheduler
def print_t[]:
  pass

sched = BlockingScheduler[]
sched.add_job[print_t, 'interval', seconds =60] #will do the print_t work for every 60 seconds

sched.start[]

Phương pháp số 4. Sử dụng mô-đun luồng để thực thi một chức năng sau một khoảng thời gian

Đây là mã python, nó chỉ cho bạn cách sử dụng mô-đun luồng để thực thi một chức năng sau một khoảng thời gian. Bạn có thể kiểm tra nó


import threading 
import time

class RepeatedTimer[object]:
  def __init__[self, interval, function, *args, **kwargs]:
    self._timer = None
    self.interval = interval
    self.function = function
    self.args = args
    self.kwargs = kwargs
    self.is_running = False
    self.next_call = time.time[]
    self.start[]

  def _run[self]:
    self.is_running = False
    self.start[]
    self.function[*self.args, **self.kwargs]

  def start[self]:
    if not self.is_running:
      self.next_call += self.interval
      self._timer = threading.Timer[self.next_call - time.time[], self._run]
      self._timer.start[]
      self.is_running = True

  def stop[self]:
    self._timer.cancel[]
    self.is_running = False

Những bài viết liên quan

  • Hơn 20 cuốn sách Python
  • Tải xuống tệp lớn trong python với các yêu cầu
  • Giải mã dữ liệu XDR bằng Python

Trò chuyện với tôi

Tôi hy vọng bạn thích Hướng dẫn Python này💗. Bây giờ, đừng ngần ngại để lại tin nhắn tại haxratali0@gamil. com. Tôi trả lời mọi thư tôi nhận được. tôi sẽ rất vui được trò chuyện với bạn

Sử dụng hàm

import sched, time
s = sched.scheduler[time.time, time.sleep]
def do_something[sc]: 
    print["Doing stuff..."]
    # do your stuff
    sc.enter[60, 1, do_something, [sc,]]

s.enter[60, 1, do_something, [s,]]
s.run[]
0 để chạy một hàm Python nhiều lần trong các công cụ Python do môi trường cơ sở dữ liệu tạo ra

Cú pháp của hàm như sau

oml.index_apply[times, func, func_owner=None, parallel=None, graphics=False, **kwargs]

Đối số

import sched, time
s = sched.scheduler[time.time, time.sleep]
def do_something[sc]: 
    print["Doing stuff..."]
    # do your stuff
    sc.enter[60, 1, do_something, [sc,]]

s.enter[60, 1, do_something, [s,]]
s.run[]
1 là một
import sched, time
s = sched.scheduler[time.time, time.sleep]
def do_something[sc]: 
    print["Doing stuff..."]
    # do your stuff
    sc.enter[60, 1, do_something, [sc,]]

s.enter[60, 1, do_something, [s,]]
s.run[]
2 chỉ định số lần chạy hàm
import sched, time
s = sched.scheduler[time.time, time.sleep]
def do_something[sc]: 
    print["Doing stuff..."]
    # do your stuff
    sc.enter[60, 1, do_something, [sc,]]

s.enter[60, 1, do_something, [s,]]
s.run[]
3

Đối số

import sched, time
s = sched.scheduler[time.time, time.sleep]
def do_something[sc]: 
    print["Doing stuff..."]
    # do your stuff
    sc.enter[60, 1, do_something, [sc,]]

s.enter[60, 1, do_something, [s,]]
s.run[]
3 là chức năng để chạy. Nó có thể là một trong những điều sau đây

  • Một hàm Python

  • Một chuỗi là tên của hàm Python do người dùng định nghĩa trong OML4Py kho lưu trữ tập lệnh

  • Một chuỗi xác định hàm Python
  • Một đối tượng

    import sched, time
    s = sched.scheduler[time.time, time.sleep]
    def do_something[sc]: 
        print["Doing stuff..."]
        # do your stuff
        sc.enter[60, 1, do_something, [sc,]]
    
    s.enter[60, 1, do_something, [s,]]
    s.run[]
    5 được trả về bởi hàm
    import sched, time
    s = sched.scheduler[time.time, time.sleep]
    def do_something[sc]: 
        print["Doing stuff..."]
        # do your stuff
        sc.enter[60, 1, do_something, [sc,]]
    
    s.enter[60, 1, do_something, [s,]]
    s.run[]
    6

Đối số

import oml
import pandas as pd

def compute_random_mean[index]:
    import numpy as np
    import scipy
    from statistics import mean 
    np.random.seed[index]
    res = np.random.random[[100,1]]*10
    return mean[res[1]]
res = oml.index_apply[times=10, func=compute_random_mean]
type[res]
res
0 tùy chọn là một chuỗi hoặc
import oml
import pandas as pd

def compute_random_mean[index]:
    import numpy as np
    import scipy
    from statistics import mean 
    np.random.seed[index]
    res = np.random.random[[100,1]]*10
    return mean[res[1]]
res = oml.index_apply[times=10, func=compute_random_mean]
type[res]
res
1 [mặc định] chỉ định chủ sở hữu của hàm Python do người dùng xác định đã đăng ký khi đối số
import sched, time
s = sched.scheduler[time.time, time.sleep]
def do_something[sc]: 
    print["Doing stuff..."]
    # do your stuff
    sc.enter[60, 1, do_something, [sc,]]

s.enter[60, 1, do_something, [s,]]
s.run[]
3 là tên hàm Python do người dùng xác định đã đăng ký

Đối số

import oml
import pandas as pd

def compute_random_mean[index]:
    import numpy as np
    import scipy
    from statistics import mean 
    np.random.seed[index]
    res = np.random.random[[100,1]]*10
    return mean[res[1]]
res = oml.index_apply[times=10, func=compute_random_mean]
type[res]
res
3 là một giá trị boolean,
import sched, time
s = sched.scheduler[time.time, time.sleep]
def do_something[sc]: 
    print["Doing stuff..."]
    # do your stuff
    sc.enter[60, 1, do_something, [sc,]]

s.enter[60, 1, do_something, [s,]]
s.run[]
2 hoặc
import oml
import pandas as pd

def compute_random_mean[index]:
    import numpy as np
    import scipy
    from statistics import mean 
    np.random.seed[index]
    res = np.random.random[[100,1]]*10
    return mean[res[1]]
res = oml.index_apply[times=10, func=compute_random_mean]
type[res]
res
1 [mặc định] chỉ định mức độ song song ưu tiên để sử dụng trong công việc Thực thi Python nhúng. Giá trị có thể là một trong những giá trị sau

  • Một số nguyên dương lớn hơn hoặc bằng 1 cho một mức độ song song cụ thể

  • import oml
    import pandas as pd
    
    def compute_random_mean[index]:
        import numpy as np
        import scipy
        from statistics import mean 
        np.random.seed[index]
        res = np.random.random[[100,1]]*10
        return mean[res[1]]
    res = oml.index_apply[times=10, func=compute_random_mean]
    type[res]
    res
    6,
    import oml
    import pandas as pd
    
    def compute_random_mean[index]:
        import numpy as np
        import scipy
        from statistics import mean 
        np.random.seed[index]
        res = np.random.random[[100,1]]*10
        return mean[res[1]]
    res = oml.index_apply[times=10, func=compute_random_mean]
    type[res]
    res
    1, hoặc
    import oml
    import pandas as pd
    
    def compute_random_mean[index]:
        import numpy as np
        import scipy
        from statistics import mean 
        np.random.seed[index]
        res = np.random.random[[100,1]]*10
        return mean[res[1]]
    res = oml.index_apply[times=10, func=compute_random_mean]
    type[res]
    res
    8 không song song

  • import oml
    import pandas as pd
    
    def compute_random_mean[index]:
        import numpy as np
        import scipy
        from statistics import mean 
        np.random.seed[index]
        res = np.random.random[[100,1]]*10
        return mean[res[1]]
    res = oml.index_apply[times=10, func=compute_random_mean]
    type[res]
    res
    9 cho tính song song dữ liệu mặc định

Đối số

import time
starttime = time.time[]
while True:
    print["tick"]
    time.sleep[60.0 - [[time.time[] - starttime] % 60.0]]
40 là một giá trị boolean chỉ định có tìm kiếm hình ảnh hay không. Giá trị mặc định là
import oml
import pandas as pd

def compute_random_mean[index]:
    import numpy as np
    import scipy
    from statistics import mean 
    np.random.seed[index]
    res = np.random.random[[100,1]]*10
    return mean[res[1]]
res = oml.index_apply[times=10, func=compute_random_mean]
type[res]
res
9

Với tham số

import time
starttime = time.time[]
while True:
    print["tick"]
    time.sleep[60.0 - [[time.time[] - starttime] % 60.0]]
42, bạn có thể truyền các đối số bổ sung cho hàm
import sched, time
s = sched.scheduler[time.time, time.sleep]
def do_something[sc]: 
    print["Doing stuff..."]
    # do your stuff
    sc.enter[60, 1, do_something, [sc,]]

s.enter[60, 1, do_something, [s,]]
s.run[]
3. Các đối số kiểm soát đặc biệt, bắt đầu bằng
import time
starttime = time.time[]
while True:
    print["tick"]
    time.sleep[60.0 - [[time.time[] - starttime] % 60.0]]
44, không được chuyển đến hàm được chỉ định bởi
import sched, time
s = sched.scheduler[time.time, time.sleep]
def do_something[sc]: 
    print["Doing stuff..."]
    # do your stuff
    sc.enter[60, 1, do_something, [sc,]]

s.enter[60, 1, do_something, [s,]]
s.run[]
3, mà thay vào đó kiểm soát những gì xảy ra trước hoặc sau khi chạy hàm

Xem thêm . Giới thiệu về Đối số kiểm soát đặc biệt

Hàm

import sched, time
s = sched.scheduler[time.time, time.sleep]
def do_something[sc]: 
    print["Doing stuff..."]
    # do your stuff
    sc.enter[60, 1, do_something, [sc,]]

s.enter[60, 1, do_something, [s,]]
s.run[]
0 trả về danh sách đối tượng Python hoặc danh sách đối tượng
import time
starttime = time.time[]
while True:
    print["tick"]
    time.sleep[60.0 - [[time.time[] - starttime] % 60.0]]
47. Nếu không có hình ảnh nào được hiển thị trong hàm Python do người dùng xác định, thì
import sched, time
s = sched.scheduler[time.time, time.sleep]
def do_something[sc]: 
    print["Doing stuff..."]
    # do your stuff
    sc.enter[60, 1, do_something, [sc,]]

s.enter[60, 1, do_something, [s,]]
s.run[]
0 sẽ trả về một danh sách các đối tượng Python do hàm Python do người dùng xác định trả về. Mặt khác, nó trả về một danh sách các đối tượng
import time
starttime = time.time[]
while True:
    print["tick"]
    time.sleep[60.0 - [[time.time[] - starttime] % 60.0]]
47

Xem thêm . Giới thiệu về đầu ra

Ví dụ 10-10 Sử dụng oml. hàm index_apply

Ví dụ này định nghĩa một hàm trả về giá trị trung bình của một tập hợp các số ngẫu nhiên theo số lần đã chỉ định

Làm cách nào để chương trình chạy trong một khoảng thời gian nhất định Python?

Nếu bạn có một chương trình Python và bạn muốn nó chờ, bạn có thể sử dụng một hàm đơn giản như hàm này. thời gian. sleep[x] trong đó x là số giây mà bạn muốn chương trình của mình đợi.

Thời gian time[] trong Python là gì?

Phương thức time[] của Python . Lưu ý - Mặc dù thời gian luôn được trả về dưới dạng số dấu phẩy động, nhưng không phải tất cả các hệ thống đều cung cấp thời gian với độ chính xác cao hơn 1 giây. returns the time as a floating point number expressed in seconds since the epoch, in UTC. Note − Even though the time is always returned as a floating point number, not all systems provide time with a better precision than 1 second.

Chủ Đề