怎样实现任务提醒脚本

wen 实用脚本 23

本文目录导读:

怎样实现任务提醒脚本

  1. 基础Python定时提醒脚本
  2. 简单命令行版本
  3. Web版定时提醒(使用Flask)
  4. 使用schedule库的高级版本
  5. 安装依赖
  6. 使用建议

我来教你实现一个任务提醒脚本,提供几种不同场景的方案:

基础Python定时提醒脚本

import time
import datetime
import os
import sys
import json
from threading import Timer
class TaskReminder:
    def __init__(self):
        self.tasks = []
        self.load_tasks()
    def add_task(self, task_name, remind_time, repeat=False):
        """添加任务提醒
        :param task_name: 任务名称
        :param remind_time: 提醒时间(格式:HH:MM 或 时间戳)
        :param repeat: 是否重复提醒
        """
        task = {
            'name': task_name,
            'time': remind_time,
            'repeat': repeat,
            'completed': False
        }
        self.tasks.append(task)
        self.save_tasks()
        print(f"✅ 任务已添加: {task_name} 提醒时间: {remind_time}")
    def load_tasks(self):
        """加载保存的任务"""
        try:
            with open('tasks.json', 'r', encoding='utf-8') as f:
                self.tasks = json.load(f)
        except FileNotFoundError:
            self.tasks = []
    def save_tasks(self):
        """保存任务到文件"""
        with open('tasks.json', 'w', encoding='utf-8') as f:
            json.dump(self.tasks, f, ensure_ascii=False, indent=2)
    def check_tasks(self):
        """检查是否有任务需要提醒"""
        current_time = datetime.datetime.now()
        current_time_str = current_time.strftime("%H:%M")
        for task in self.tasks[:]:  # 使用副本遍历
            if task['completed']:
                continue
            # 检查时间是否匹配
            if task['time'] == current_time_str or \
               (isinstance(task['time'], (int, float)) and 
                current_time.timestamp() >= task['time']):
                self.remind(task['name'])
                if not task['repeat']:
                    task['completed'] = True
                else:
                    # 重复任务:设置明天同一时间
                    if isinstance(task['time'], str):
                        tomorrow = current_time + datetime.timedelta(days=1)
                        next_remind = tomorrow.strftime("%Y-%m-%d ") + task['time']
                        task['last_reminded'] = current_time_str
        self.save_tasks()
    def remind(self, task_name):
        """执行提醒"""
        print(f"\n🔔 提醒: {task_name}")
        print(f"   时间: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M')}")
        # Windows系统弹窗
        if sys.platform == 'win32':
            import ctypes
            ctypes.windll.user32.MessageBoxW(0, 
                f"任务提醒: {task_name}", 
                "⏰ 提醒", 0)
        # macOS系统通知
        elif sys.platform == 'darwin':
            os.system(f"""
                osascript -e 'display notification "{task_name}" with title "任务提醒"'
            """)
        # Linux系统通知
        elif sys.platform.startswith('linux'):
            os.system(f'notify-send "任务提醒" "{task_name}"')
    def start(self):
        """启动提醒监控"""
        print("📋 任务提醒系统已启动...")
        print("按 Ctrl+C 停止")
        try:
            while True:
                self.check_tasks()
                time.sleep(30)  # 每30秒检查一次
        except KeyboardInterrupt:
            print("\n👋 任务提醒系统已停止")
    def show_tasks(self):
        """显示所有任务"""
        if not self.tasks:
            print("暂无任务")
            return
        print("\n📋 当前任务列表:")
        for i, task in enumerate(self.tasks, 1):
            status = "✅" if task['completed'] else "⏳"
            repeat = "🔄" if task['repeat'] else ""
            print(f"{i}. {status} {task['name']} - {task['time']} {repeat}")
    def remove_task(self, index):
        """删除任务"""
        if 0 <= index < len(self.tasks):
            removed = self.tasks.pop(index)
            self.save_tasks()
            print(f"🗑️ 已删除: {removed['name']}")
        else:
            print("❌ 无效的任务编号")
# 使用示例
if __name__ == "__main__":
    reminder = TaskReminder()
    # 添加任务
    reminder.add_task("开会", "09:00", repeat=True)
    reminder.add_task("吃药", "12:00")
    reminder.add_task("运动", "18:30", repeat=True)
    # 启动提醒
    reminder.start()

简单命令行版本

import time
import datetime
def simple_reminder():
    """简单版命令行提醒"""
    reminders = {}
    print("=== 简单任务提醒 ===")
    print("格式: 任务名称 提醒时间(HH:MM)")
    print("示例: 开会 09:00")
    print("输入 'q' 退出\n")
    # 添加提醒
    while True:
        user_input = input("添加提醒: ")
        if user_input.lower() == 'q':
            break
        try:
            name, time_str = user_input.rsplit(' ', 1)
            reminders[time_str] = name
            print(f"✅ 已添加: {time_str} - {name}")
        except:
            print("❌ 格式错误,请使用: 任务名称 HH:MM")
    print(f"\n📋 共 {len(reminders)} 个提醒,开始监控...")
    # 监控提醒
    try:
        while True:
            current_time = datetime.datetime.now().strftime("%H:%M")
            if current_time in reminders:
                print(f"\n🔔 {current_time} - {reminders[current_time]}")
                del reminders[current_time]
            if not reminders:
                print("所有提醒已完成")
                break
            time.sleep(10)
    except KeyboardInterrupt:
        print("\n已停止")
# 运行
if __name__ == "__main__":
    simple_reminder()

Web版定时提醒(使用Flask)

from flask import Flask, request, jsonify, render_template_string
import datetime
import threading
import time
app = Flask(__name__)
# 存储任务的简单数据结构
tasks = []
lock = threading.Lock()
# HTML模板
HTML_TEMPLATE = '''
<!DOCTYPE html>
<html>
<head>任务提醒系统</title>
    <style>
        body { font-family: Arial; max-width: 800px; margin: 20px auto; padding: 20px; }
        .task { border: 1px solid #ddd; padding: 15px; margin: 10px 0; border-radius: 5px; }
        .reminded { background-color: #e8f5e9; }
        .pending { background-color: #fff3e0; }
        button { margin: 5px; padding: 5px 10px; }
        input { margin: 5px; padding: 5px; }
    </style>
</head>
<body>
    <h1>📋 任务提醒系统</h1>
    <div style="margin: 20px 0;">
        <input type="text" id="taskName" placeholder="任务名称">
        <input type="time" id="taskTime">
        <button onclick="addTask()">添加任务</button>
    </div>
    <div id="taskList">
        {% for task in tasks %}
        <div class="task {% if task.reminded %}reminded{% else %}pending{% endif %}">
            <strong>{{ task.name }}</strong> - {{ task.time }}
            {% if task.reminded %}
            <span style="color: green;">✅ 已提醒</span>
            {% else %}
            <span style="color: orange;">⏳ 待提醒</span>
            {% endif %}
            <button onclick="deleteTask({{ loop.index0 }})">删除</button>
        </div>
        {% endfor %}
    </div>
    <script>
        function addTask() {
            const name = document.getElementById('taskName').value;
            const time = document.getElementById('taskTime').value;
            fetch('/add_task', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({name: name, time: time})
            })
            .then(response => response.json())
            .then(data => {
                if(data.success) location.reload();
                else alert('添加失败');
            });
        }
        function deleteTask(index) {
            fetch('/delete_task/' + index, {method: 'DELETE'})
            .then(response => response.json())
            .then(data => {
                if(data.success) location.reload();
            });
        }
        // 自动刷新
        setInterval(() => {
            fetch('/get_tasks')
            .then(response => response.json())
            .then(data => {
                const taskList = document.getElementById('taskList');
                // 更新页面显示
            });
        }, 5000);
    </script>
</body>
</html>
'''
@app.route('/')
def index():
    return render_template_string(HTML_TEMPLATE, tasks=tasks)
@app.route('/add_task', methods=['POST'])
def add_task():
    data = request.json
    task = {
        'name': data['name'],
        'time': data['time'],
        'reminded': False
    }
    with lock:
        tasks.append(task)
    return jsonify({'success': True})
@app.route('/delete_task/<int:index>', methods=['DELETE'])
def delete_task(index):
    with lock:
        if 0 <= index < len(tasks):
            tasks.pop(index)
            return jsonify({'success': True})
    return jsonify({'success': False}), 400
@app.route('/get_tasks')
def get_tasks():
    return jsonify(tasks)
@app.route('/check_reminders')
def check_reminders():
    """检查是否需要提醒的API"""
    current_time = datetime.datetime.now().strftime("%H:%M")
    reminded = []
    with lock:
        for task in tasks:
            if not task['reminded'] and task['time'] == current_time:
                task['reminded'] = True
                reminded.append(task)
    return jsonify({'reminded': reminded})
if __name__ == '__main__':
    app.run(debug=True, port=5000)

使用schedule库的高级版本

import schedule
import time
import datetime
import winsound  # Windows系统
import os
def remind_task(name):
    """执行提醒"""
    timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    print(f"\n🔔 [{timestamp}] 提醒: {name}")
    # 播放声音
    try:
        winsound.Beep(1000, 500)
    except:
        pass
    # 系统通知
    if os.name == 'nt':  # Windows
        try:
            from plyer import notification
            notification.notify(
                title="任务提醒",
                message=name,
                timeout=5
            )
        except:
            pass
def setup_daily_tasks():
    """设置每日任务"""
    # 工作日任务
    schedule.every().monday.at("09:00").do(remind_task, "周一晨会")
    schedule.every().tuesday.at("09:00").do(remind_task, "周二晨会")
    # 每日任务
    schedule.every().day.at("08:00").do(remind_task, "起床")
    schedule.every().day.at("12:00").do(remind_task, "午餐时间")
    schedule.every().day.at("18:00").do(remind_task, "下班时间")
    # 间隔任务
    schedule.every(2).hours.do(remind_task, "站起来活动一下")
    schedule.every(1).hour.do(remind_task, "喝水时间")
    # 特定时间
    schedule.every().day.at("22:00").do(remind_task, "准备睡觉")
def main():
    print("📋 智能任务提醒系统")
    print(f"启动时间: {datetime.datetime.now()}")
    print("正在监控任务...\n")
    setup_daily_tasks()
    while True:
        schedule.run_pending()
        time.sleep(30)
if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\n👋 提醒系统已关闭")

安装依赖

根据你选择的方案,安装相应依赖:

# 基础版本无需额外安装
# Web版本
pip install flask
# 高级版本
pip install schedule plyer
# 如果需要更完整的通知功能
pip install pywin32  # Windows

使用建议

  1. 选择合适方案

    • 简单任务:使用基础Python脚本
    • 团队协作:使用Web版本
    • 定时任务:使用schedule版本
  2. 持久化存储

    • 使用JSON文件保存任务
    • 考虑使用SQLite或数据库
  3. 增强功能

    • 添加邮件提醒
    • 集成短信通知
    • 支持语音播报
    • 日历同步功能
  4. 部署方式

    • 作为系统服务运行
    • 使用Docker容器化
    • 部署到云服务器

需要我帮你定制某个特定版本或添加特定功能吗?

抱歉,评论功能暂时关闭!