亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

線程在 python 中中斷睡眠(來自 java 的端口)

線程在 python 中中斷睡眠(來自 java 的端口)

侃侃爾雅 2023-02-22 15:13:59
我有以下 Java 類,我想(在概念上)移植到 python。這個想法是你有一個鬧鐘線程,它會休眠 x 秒(直到第二天早上),除非設置了新的喚醒時間,此時休眠線程被中斷,新的剩余時間被設置并且它在那個時間休眠。如果完成休眠,則觸發鬧鐘聲音并等待設置新的喚醒時間我想將它移植到 Python,但我只花了幾個小時在谷歌上搜索,雖然有 1001 種方法可以在 Python 中管理線程和休眠,但我找不到如何讓 sleep() 持續 x 秒但也發送中斷的方法。需要明確的是,我不需要有人為我編寫整個類,只需一個簡單的睡眠和中斷示例就足夠了,這樣我就可以理解它在 Python 中的完成方式。package com.njitram.bedroomtunes.server.alarm;import java.text.SimpleDateFormat;import java.util.Calendar;import com.njitram.bedroomtunes.log.Logger;public class AlarmThread extends Thread {    private Calendar wakeupTime;    private Alarm alarm;        /*     * Constructor to disable the alarm     */    public AlarmThread(Alarm alarm) {        this(null, alarm);    }        public AlarmThread(Calendar wakeupTime, Alarm alarm) {        this.alarm = alarm;        if(wakeupTime == null) {            disable();        } else {            setNewWakeUpTime(wakeupTime);        }        this.start();    }        public void setNewWakeUpTime(Calendar wakeupTime) {        Logger.log("New Wake time set for AlarmThread: " + new SimpleDateFormat("dd-MM-yyyy HH:mm:ss").format(wakeupTime.getTime()));        this.wakeupTime = wakeupTime;        // If the thread was already started, it will be sleeping. Wake it up and recalculate how long it needs to sleep. Interrupting will achieve this.        this.interrupt();    }        public void disable() {        setNewWakeUpTime(getDisabledTime());    }        private Calendar getDisabledTime() {        // The idea is to disable the alarm. If the alarm eventually goes off in the year 3000, I deserve to wake up...        Calendar wakeupTime = Calendar.getInstance();        wakeupTime.set(Calendar.YEAR, 3000);        return wakeupTime;    }   
查看完整描述

1 回答

?
千萬里不及你

TA貢獻1784條經驗 獲得超9個贊

APScheduler包似乎提供您正在尋找的功能。用戶指南應包含有關設置和刪除計劃所需的所有功能的信息。

請注意,這與您的睡眠方法不同,它使用調度來代替 - 盡管我建議不要“忙著睡覺”,因為它會浪費 CPU 周期


查看完整回答
反對 回復 2023-02-22
  • 1 回答
  • 0 關注
  • 139 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號