首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >python中特定时间的提醒

python中特定时间的提醒
EN

Stack Overflow用户
提问于 2021-11-16 21:35:25
回答 2查看 88关注 0票数 0

我需要写一个python程序,让我在特定的时间设置提醒,例如“记得下午2点拿出垃圾箱”,但我只能在一定的时间长度内设置提醒,而不是给定的时间。我还需要能够设置多个提醒多次。如有任何帮助,我们将不胜感激:)

EN

回答 2

Stack Overflow用户

发布于 2021-11-16 21:43:53

这看起来像是家庭作业,所以你需要自己写代码。

  1. ,你知道现在几点了。你知道下午2点是什么时候。从现在到下午2点有多长时间?睡那么长时间。

  1. 保存所有待定报警的列表。找到最早的警报。将其从列表中删除。一直睡到闹钟响起。重复

如果使用适当的数据结构,如heapq或PriorityQueue,您可能会发现步骤2更容易。但是,如果警报的数量很少,那么列表就可以了。

票数 2
EN

Stack Overflow用户

发布于 2021-12-11 06:11:55

下面每秒钟检查一次新的提醒,尽管在阅读Frank的答案后,这将是一个更好的解决方案,最好的解决方案是根本不使用Python,并让操作系统通过创建cron作业或在Windows上创建计划任务来管理这一点。

代码语言:javascript
复制
reminders = [
    # Put all of your reminders here
    ('2021-11-16 02:44:00', 'Take out the garbage'),
    ('2021-11-17 04:22:00', 'Another reminder')
]

from datetime import datetime
import time

# For performance reasons it's best to perform whatever computations we can before we go into our infinite loop
# In this case let's calculate all of the timestamps
reminders2 = {datetime.fromisoformat(reminder[0]).timestamp(): reminder[1] for reminder in reminders}

while True:
    now = time.time()
    for timestamp, reminder_msg in reminders2.items():
        if timestamp < now:
            print(reminder_msg)
            del reminders2[timestamp]
            # we're not in any hurry, instead of worrying about the consequences of deleting something from the same dictionary we are iterating over
            # we can just break and wait for the next go around of the while loop to finish checking the remaining reminders
            break
    time.sleep(1) # in seconds
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69996306

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档