定时切换显示模式脚本怎么写

wen 实用脚本 3

本文目录导读:

定时切换显示模式脚本怎么写

  1. 网页版(暗黑模式/亮色模式切换)
  2. Windows 系统(使用 PowerShell)
  3. macOS 系统(使用 Bash)
  4. 自定义时间段的通用版本
  5. 浏览器扩展版本(manifest v3)
  6. 使用建议:

我来帮你编写一个定时切换显示模式的脚本,这里提供几种常见场景的解决方案:

网页版(暗黑模式/亮色模式切换)

// 定时切换暗黑模式脚本
function toggleTheme() {
    const currentHour = new Date().getHours();
    const body = document.body;
    // 18:00-6:00 使用暗黑模式,其他时间使用亮色模式
    if (currentHour >= 18 || currentHour < 6) {
        body.classList.add('dark-mode');
        body.classList.remove('light-mode');
        console.log('切换到暗黑模式');
    } else {
        body.classList.add('light-mode');
        body.classList.remove('dark-mode');
        console.log('切换到亮色模式');
    }
}
// 立即执行一次
toggleTheme();
// 每30分钟检查一次
setInterval(toggleTheme, 30 * 60 * 1000);

HTML样式配合:

<style>
    .light-mode {
        background-color: #ffffff;
        color: #333333;
    }
    .dark-mode {
        background-color: #1a1a1a;
        color: #ffffff;
    }
    body {
        transition: background-color 0.5s, color 0.5s;
    }
</style>

Windows 系统(使用 PowerShell)

# 定时切换 Windows 深色模式
$theme = Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize" -Name "AppsUseLightTheme"
function Switch-Theme {
    $hour = (Get-Date).Hour
    if ($hour -ge 18 -or $hour -lt 7) {
        # 切换到深色模式 (值为0)
        Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize" -Name "AppsUseLightTheme" -Value 0
        Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize" -Name "SystemUsesLightTheme" -Value 0
        Write-Host "切换到深色模式" -ForegroundColor Cyan
    } else {
        # 切换到浅色模式 (值为1)
        Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize" -Name "AppsUseLightTheme" -Value 1
        Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize" -Name "SystemUsesLightTheme" -Value 1
        Write-Host "切换到浅色模式" -ForegroundColor Yellow
    }
}
# 首次执行
Switch-Theme
# 创建定时任务(每1小时检查一次)
$action = New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "-File `"$PSCommandPath`""
$trigger = New-ScheduledTaskTrigger -Daily -At "00:00" -RepetitionInterval (New-TimeSpan -Minutes 60)
$principal = New-ScheduledTaskPrincipal -UserId "$env:USERNAME" -RunLevel Highest
Register-ScheduledTask -TaskName "ThemeSwitcher" -Action $action -Trigger $trigger -Principal $principal -Force
Write-Host "定时任务已创建!"

macOS 系统(使用 Bash)

#!/bin/bash
# 定时切换 macOS 深色模式脚本
CURRENT_HOUR=$(date +%H)
# 设置切换时间(18:00-7:00 使用深色模式)
if [ "$CURRENT_HOUR" -ge 18 ] || [ "$CURRENT_HOUR" -lt 7 ]; then
    osascript -e 'tell application "System Events" to tell appearance preferences to set dark mode to true'
    echo "切换到深色模式"
else
    osascript -e 'tell application "System Events" to tell appearance preferences to set dark mode to false'
    echo "切换到亮色模式"
fi

创建 plist 定时任务:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.user.themeswitcher</string>
    <key>ProgramArguments</key>
    <array>
        <string>/path/to/theme-switcher.sh</string>
    </array>
    <key>StartInterval</key>
    <integer>1800</integer>
    <key>RunAtLoad</key>
    <true/>
</dict>
</plist>

自定义时间段的通用版本

import time
import schedule
from datetime import datetime
def switch_display_mode():
    current_time = datetime.now()
    current_hour = current_time.hour
    # 自定义时间段
    dark_mode_start = 18  # 下午6点
    dark_mode_end = 7     # 早上7点
    if current_hour >= dark_mode_start or current_hour < dark_mode_end:
        print(f"[{current_time.strftime('%H:%M:%S')}] 切换到深色模式")
        # 在这里添加切换显示模式的代码
        # 修改注册表、调用系统API等
    else:
        print(f"[{current_time.strftime('%H:%M:%S')}] 切换到亮色模式")
        # 在这里添加切换显示模式的代码
# 立即执行一次
switch_display_mode()
# 每30分钟检查一次
schedule.every(30).minutes.do(switch_display_mode)
# 持续运行
while True:
    schedule.run_pending()
    time.sleep(1)

浏览器扩展版本(manifest v3)

manifest.json:

{
  "manifest_version": 3,
  "name": "Auto Theme Switcher",
  "version": "1.0",
  "permissions": ["storage", "alarms"],
  "background": {
    "service_worker": "background.js"
  },
  "content_scripts": [{
    "matches": ["<all_urls>"],
    "js": ["content.js"]
  }]
}

background.js:

// 设置定时检查
chrome.alarms.create('checkTheme', {
    periodInMinutes: 30
});
chrome.alarms.onAlarm.addListener((alarm) => {
    if (alarm.name === 'checkTheme') {
        const hour = new Date().getHours();
        const isDark = hour >= 18 || hour < 7;
        chrome.tabs.query({}, (tabs) => {
            tabs.forEach(tab => {
                chrome.tabs.sendMessage(tab.id, {
                    action: 'toggleTheme',
                    isDark: isDark
                });
            });
        });
    }
});

使用建议:

  1. 选择适合的方案:根据你的操作系统和需求选择合适的版本
  2. 调整时间设置:修改 dark_mode_startdark_mode_end 变量自定义切换时间
  3. 检查频率:根据需求调整检查间隔(建议10-30分钟)
  4. 添加过渡动画:使用CSS过渡效果让切换更平滑
  5. 保存用户偏好:允许用户覆盖自动切换

需要我针对特定平台或场景进行详细说明吗?

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