通过 Python 实现定时打开链接的功能

通过简单的GUI库,实现了Python的小工具制作:

源码如下:

import PySimpleGUI as sg
import webbrowser
import threading
import time

path = r"./duola.ico"

# 定义GUI布局
layout = [
    [sg.Text("执行时间:")],
    [sg.InputText(size=(5, 1), key='HOUR'), sg.Text("时"),
     sg.InputText(size=(5, 1), key='MINUTE'), sg.Text("分"),
     sg.InputText(size=(5, 1), key='SECOND'), sg.Text("秒")],
    [sg.Text("")],
    [sg.Text("网址信息:")],
    [sg.InputText(size=(30, 1), key='URL')],
    [sg.Text("")],
    [sg.Text("距离任务执行还剩:"), sg.Text(size=(8, 1), key='TIMER')],
    [sg.Text("")],
    [sg.Button('开始'), sg.Button('取消'), sg.Button('退出'), sg.Button('清空')],

]

# 全局变量,用于标记是否终止定时任务和存储定时任务线程
terminate_flag = False
timer_thread = None

# 创建GUI窗口
window = sg.Window('tomato', layout, finalize=True, resizable=True, grab_anywhere=True)

# 修改图标
window.TKroot.iconbitmap(path)


def openTip():
    layout = [
        [sg.Text('')],
        [sg.Text('=== 任务已完成 ===')],
        [sg.Text('')],
    ]

    # 创建弹出窗口并设置图标
    window = sg.Window('任务进度', layout, icon=path)  # 将path_to_icon.ico替换为你的图标文件的路径

    # 事件循环
    while True:
        event, values = window.read()
        if event == sg.WIN_CLOSED:
            break

    # 关闭弹出窗口
    window.close()


def open_url_at_time(url, hour, minute, second, timer_element):
    global terminate_flag
    # 获取当前时间
    current_time = time.localtime()
    target_time = time.struct_time((current_time.tm_year, current_time.tm_mon, current_time.tm_mday, int(hour),
                                    int(minute), int(second), current_time.tm_wday, current_time.tm_yday,
                                    current_time.tm_isdst))

    # 计算距离目标时间的秒数
    time_difference = int(time.mktime(target_time) - time.mktime(current_time))
    while time_difference > 0 and not terminate_flag:
        timer_element.update(f'{time_difference} 秒')
        time.sleep(1)
        time_difference -= 1

    # 如果未被终止,打开默认浏览器访问网址
    if not terminate_flag:
        webbrowser.open(url)
        # 创建弹出窗口
        openTip()


while True:
    event, values = window.read()

    if event == sg.WIN_CLOSED or event == '退出':
        break
    elif event == '开始':
        # 获取用户输入的任务执行时间和网址
        hour = values['HOUR']
        minute = values['MINUTE']
        second = values['SECOND']
        url = values['URL']

        # 创建定时任务线程
        timer_thread = threading.Thread(target=open_url_at_time,
                                        args=[url, hour, minute, second, window.FindElement('TIMER')])
        timer_thread.start()
    elif event == '取消':
        # 终止当前正在执行的定时任务
        terminate_flag = True
        window.FindElement('TIMER').update('任务已被终止')
    elif event == '清空':
        # 清空用户输入
        window.FindElement('HOUR').update('')
        window.FindElement('MINUTE').update('')
        window.FindElement('SECOND').update('')
        window.FindElement('URL').update('')

# 关闭定时任务线程(如果存在)
if timer_thread and timer_thread.is_alive():
    terminate_flag = True
    timer_thread.join()

# 关闭GUI窗口
window.close()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python可以使用`pymysql`库连MySQL数据库,并且使用`crontab`或者`apscheduler`模块来实现定时备份。 具体实现步骤如下: 1. 安装`pymysql`库:可以使用pip安装 ```python pip install pymysql ``` 2. 编写备份脚本 ```python import pymysql import os import time # 数据库连信息 host = 'localhost' port = 3306 user = 'root' password = 'password' database = 'database' # 备份文件路径 backup_path = '/data/mysql_backup/' # 获取当前时间字符串 def get_current_time(): return time.strftime('%Y%m%d_%H%M%S', time.localtime(time.time())) # 备份数据库 def backup_database(): # 创建备份文件夹 if not os.path.exists(backup_path): os.makedirs(backup_path) # 连数据库 conn = pymysql.connect(host=host, port=port, user=user, password=password, database=database) cursor = conn.cursor() # 获取所有表名 cursor.execute('show tables') tables = cursor.fetchall() # 备份每张表 for table in tables: table_name = table[0] file_name = backup_path + database + '_' + table_name + '_' + get_current_time() + '.sql' cmd = 'mysqldump -h' + host + ' -P' + str(port) + ' -u' + user + ' -p' + password + ' ' + database + ' ' + table_name + ' > ' + file_name os.system(cmd) # 关闭数据库连 cursor.close() conn.close() if __name__ == '__main__': backup_database() ``` 3. 配置定时任务 使用`crontab`或者`apscheduler`模块可以实现定时任务。在Linux系统中,可以使用以下命令打开`crontab`配置文件: ```python crontab -e ``` 然后添加一行如下的配置: ```python 0 0 * * * /usr/bin/python /path/to/backup.py >/dev/null 2>&1 ``` 这行配置表示每天的0点0分执行一次备份脚本。 如果使用`apscheduler`模块,可以参考以下代码: ```python from apscheduler.schedulers.blocking import BlockingScheduler scheduler = BlockingScheduler() # 添加定时任务,每天0点0分执行备份脚本 scheduler.add_job(backup_database, 'cron', day_of_week='0-6', hour=0, minute=0) # 开始执行定时任务 scheduler.start() ``` 注意:以上代码只是示例,具体实现需要根据自己的需求进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值