From e50ef0ce0652d4ba904225acdfec9b42e467d6e1 Mon Sep 17 00:00:00 2001 From: liuwei Date: Fri, 14 Feb 2025 08:58:48 +0800 Subject: [PATCH] =?UTF-8?q?=E8=B0=83=E6=95=B4=E7=99=BE=E5=BA=A6=E6=96=B0?= =?UTF-8?q?=E9=97=BB,=E5=8A=A0=E5=85=A5#=E5=8F=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- base/func_news.py | 2 +- task/dateparser_test.py | 20 ++++ task/task_list.py | 199 +++++++++++++++++++++++++++++----------- task/tasks.db | Bin 12288 -> 0 bytes task/tasks.sql | 8 ++ 5 files changed, 173 insertions(+), 56 deletions(-) create mode 100644 task/dateparser_test.py delete mode 100644 task/tasks.db create mode 100644 task/tasks.sql diff --git a/base/func_news.py b/base/func_news.py index b96be4c..0c1a920 100644 --- a/base/func_news.py +++ b/base/func_news.py @@ -104,7 +104,7 @@ class News(object): title = article['word'] # url = article['url'] # 使用f-string格式化字符串,并添加到output中 - output += f"{index}. : {title}\n" + output += f"{index} :#{title}\n" # 输出最终的字符串(这里只是为了展示,实际上你可以根据需要处理这个字符串) return output diff --git a/task/dateparser_test.py b/task/dateparser_test.py new file mode 100644 index 0000000..ffe04c4 --- /dev/null +++ b/task/dateparser_test.py @@ -0,0 +1,20 @@ +import parsedatetime as pdt +from datetime import datetime + +# 初始化 Calendar 对象 +cal = pdt.Calendar() + +def parse_natural_language_time(text): + time_struct, parse_status = cal.parse(text) + if parse_status == 1: + # 将解析后的时间结构转换为 datetime 对象 + parsed_time = datetime(*time_struct[:6]) + print(f"Parsed time: {parsed_time}") + return parsed_time + else: + print(f"Could not parse time for: {text}") + return None + +# 示例输入 +test_input = "明天上午9点开会" +parsed_time = parse_natural_language_time(test_input) diff --git a/task/task_list.py b/task/task_list.py index 3768b08..e38d0a6 100644 --- a/task/task_list.py +++ b/task/task_list.py @@ -1,68 +1,157 @@ -import sqlite3 -import datetime +import pymysql +import dateparser import schedule -import time -# SQLite数据库文件名 -DB_FILE = 'tasks.db' +# 配置数据库连接 +db_config = { + 'host': '192.168.2.32', # 替换为你的MariaDB服务器地址 + 'user': 'root', # 替换为你的MariaDB用户名 + 'password': 'lw123456', # 替换为你的MariaDB密码 + 'database': 'message_archive' +} -# 初始化数据库 -def init_db(): - conn = sqlite3.connect(DB_FILE) - c = conn.cursor() - c.execute('''CREATE TABLE IF NOT EXISTS tasks - (id INTEGER PRIMARY KEY AUTOINCREMENT, - description TEXT NOT NULL, - reminder_time TEXT NOT NULL)''') - conn.commit() - conn.close() +# 数据库连接 +def get_db_connection(): + connection = pymysql.connect(**db_config) + return connection -# 添加任务 -def add_task(description, time_str): - conn = sqlite3.connect(DB_FILE) - c = conn.cursor() - time_obj = datetime.datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S') - c.execute("INSERT INTO tasks (des cription, reminder_time) VALUES (?, ?)", - (description, time_obj.isoformat())) - conn.commit() - conn.close() - print(f"Task '{description}' added for {time_str}") +# 解析自然语言时间 +def parse_natural_language_time(text): + parsed_time = dateparser.parse(text) + return parsed_time -# 检查并执行任务 -def check_tasks(): - now = datetime.datetime.now().isoformat() - conn = sqlite3.connect(DB_FILE) - c = conn.cursor() - c.execute("SELECT * FROM tasks WHERE reminder_time <= ?", (now,)) - tasks = c.fetchall() +# 插入任务到数据库 +def insert_task_to_db(description, reminder_time, task_type): + connection = get_db_connection() + cursor = connection.cursor() + + # 插入任务信息 + query = "INSERT INTO tasks (task_description, reminder_time, task_type) VALUES (%s, %s, %s)" + cursor.execute(query, (description, reminder_time, task_type)) + connection.commit() + + cursor.close() + connection.close() + + +# 提醒任务(根据任务描述输出具体内容) +def reminder_task(task_id): + connection = get_db_connection() + cursor = connection.cursor() + + # 获取任务描述 + query = "SELECT task_description FROM tasks WHERE task_id = %s" + cursor.execute(query, (task_id,)) + task = cursor.fetchone() + + if task: + task_description = task[0] + print(f"Reminder: {task_description}") # 输出具体的任务内容 + + cursor.close() + connection.close() + + +# 调度单次任务 +def schedule_single_task(reminder_time, task_id): + schedule.every().day.at(reminder_time).do(reminder_task, task_id=task_id) + print(f"Single task scheduled at {reminder_time}.") + + +# 调度周期性任务(例如:每天执行) +def schedule_recurring_task(reminder_time, task_id): + schedule.every().day.at(reminder_time).do(reminder_task, task_id=task_id) + print(f"Recurring task scheduled every day at {reminder_time}.") + + +# 处理用户输入 +def handle_user_input(user_input, task_type): + parsed_time = parse_natural_language_time(user_input) + print(parsed_time) + if parsed_time: + formatted_time = parsed_time.strftime('%H:%M') + print(f"Scheduling task for {formatted_time}") + + # 将任务存入数据库 + insert_task_to_db(user_input, formatted_time, task_type) + + # 获取插入的任务ID + connection = get_db_connection() + cursor = connection.cursor() + cursor.execute("SELECT LAST_INSERT_ID()") + task_id = cursor.fetchone()[0] + cursor.close() + connection.commit() + connection.close() + # 根据任务类型调度任务 + if task_type == 'single': + schedule_single_task(formatted_time, task_id) + elif task_type == 'recurring': + schedule_recurring_task(formatted_time, task_id) + + +# 查询指定类型的任务 +def get_tasks_by_type(task_type): + connection = get_db_connection() + cursor = connection.cursor() + + # 查询指定类型的任务 + query = "SELECT task_id, task_description, reminder_time, status, task_type FROM tasks WHERE task_type = %s" + cursor.execute(query, (task_type,)) + + tasks = cursor.fetchall() for task in tasks: - print(f"Executing task: {task[1]}") - # 如果只想执行一次,则删除任务 - c.execute("DELETE FROM tasks WHERE id = ?", (task[0],)) - conn.commit() - conn.close() + print( + f"Task ID: {task[0]}, Description: {task[1]}, Reminder Time: {task[2]}, Status: {task[3]}, Type: {task[4]}") + + cursor.close() + connection.close() -# 定时检查任务 -schedule.every(1).minute.do(check_tasks) # 每分钟检查一次任务 +# 更新任务状态 +def update_task_status(task_id, status): + connection = get_db_connection() + cursor = connection.cursor() + + # 更新任务状态 + query = "UPDATE tasks SET status = %s WHERE task_id = %s" + cursor.execute(query, (status, task_id)) + connection.commit() + + cursor.close() + connection.close() + + +# 获取所有周期性任务 +def get_all_recurring_tasks(): + get_tasks_by_type('recurring') + + +# 获取所有单次任务 +def get_all_single_tasks(): + get_tasks_by_type('single') + + +# 主函数(示例输入) +def main(): + # 示例:单次任务 + user_input_single = "提醒我明天上午9点开会" + handle_user_input(user_input_single, 'single') + + # 示例:周期性任务 + user_input_recurring = "每天上午9点提醒我开会" + handle_user_input(user_input_recurring, 'recurring') + + # # 启动定时任务调度 + # while True: + # schedule.run_pending() + # time.sleep(1) + -# 示例使用 if __name__ == "__main__": - init_db() # 初始化数据库(如果尚未初始化) - - # 添加示例任务(注意:时间应该设置为未来的时间以测试) - add_task("Buy groceries", "2024-12-20 14:02:50") # 修改为未来时间进行测试 - add_task("Attend meeting", "2024-12-20 14:03:50") # 修改为未来时间进行测试 - - # 由于我们设置了未来的时间,因此需要使用一个足够长的时间循环来等待任务执行 - # 在实际应用中,你可能会有一个更优雅的方式来停止循环(例如监听特定事件) - print("Starting task scheduler...") - try: - while True: - schedule.run_pending() - time.sleep(1) # 等待下一分钟 - except KeyboardInterrupt: - print("Scheduler stopped manually.") \ No newline at end of file + # main() + parsed_time = dateparser.parse('每天上午9:00提醒我开会', settings={'TIMEZONE': 'Asia/Shanghai'},) + print(parsed_time) diff --git a/task/tasks.db b/task/tasks.db deleted file mode 100644 index 10d06d2ec991a4a526db937d7976cc68c6e01271..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 12288 zcmeI&K~KUk6bJAYh(r^`+pfK+5WtKLJdl_$%wmWG6iXr}f>6km4cW@Uqkcj^i8t>S z2qp{?Ph80Vt?kz3^)37D)MSqjjw=NlP6DqdnMqCwrKG|bAtb4KT=i8@b&*(2)OkMt zFOuZ)adcV!mMH4V@Q?W!)^7boKt>g;|}wvr#bVi@+6OB+FQ4)wdKg^95Zs zUbrgjx@xM}`DU@dtWw#WXU+HjH1$JNLqGrm5P$##AOHafKmY;|fB*y_uulSqG_KLb HFA0fXr5J>v diff --git a/task/tasks.sql b/task/tasks.sql new file mode 100644 index 0000000..fcbb7a4 --- /dev/null +++ b/task/tasks.sql @@ -0,0 +1,8 @@ +CREATE TABLE IF NOT EXISTS tasks ( + task_id INT AUTO_INCREMENT PRIMARY KEY, -- 任务ID,自增 + task_description VARCHAR(255) NOT NULL, -- 任务描述 + reminder_time TIME NOT NULL, -- 提醒时间 + task_type ENUM('single', 'recurring') DEFAULT 'single', -- 任务类型:单次或周期性 + status ENUM('pending', 'completed') DEFAULT 'pending', -- 任务状态:待办或已完成 + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP -- 创建时间,默认为当前时间 +);