【问题标题】:Batch File To Execute Between Specific Times在特定时间之间执行的批处理文件
【发布时间】:2021-09-22 08:47:24
【问题描述】:

我有一个批处理文件,一旦机器能够接收到文件(这是一个变量 - 因为有些可能离线、忙碌或延迟),它就会部署到机器上,但它应该只运行当前本地时间在指定窗口内。

例如,仅在凌晨 12 点和凌晨 2 点之间。

我确实有以下与 PM 时间一起工作 - 但显然如果我在此处指定任何单(或双)数字 AM 时间(例如凌晨 1 点到上午 9 点),它将不会执行。

@echo off
SET hour=%time:~0,2%
SET shouldrun=True

IF %hour% leq 23 SET shouldrun=False
IF %hour% geq 02 SET shouldrun=False

IF "%shouldrun%"=="False" (
        echo Outside Update Schedule
        EXIT /B 1
)

IF "%shouldrun%"=="True" (
        @TASKKILL /f /im some.exe > nul 2>&1
        @timeout /t 4 > nul
         - do things here -
        @timeout /t 2 > nul
        shutdown -r -f -y -t 2
        EXIT /B 0
)

【问题讨论】:

  • 在这些时间之间使用任务计划程序运行批处理文件有什么问题?目前,如果您的脚本在晚上 11 点之前运行,它将关闭,因此必须重新启动。我认为创建脚本或可执行文件以不断运行重新启动该批处理文件没有任何好处,直到达到特定时间范围,此时已经有内置工具可以这样做。
  • 任务的性质不是重复的,并且涉及的机器太多,无法在任务管理器中设置一次性计划。通过第三方系统部署后,批处理执行并完成任务,并报告成功代码。但是,由于处理和网络延迟,可能会比预期的更晚到达或尝试运行。时间范围的重点是确保机器不会在可用窗口之外被中断,然后返回错误代码 1,以供将来定位。该批次确实可以正常工作,但不是在上午时间,我不明白为什么。
  • a) 你的%time% 是什么样的? b) 带前导零的数字按八进制处理。 0809 是无效的八进制数,因此您的 if 将失败。 c) 逻辑故障:假设现在是 01:30 (AM)。这正好在您希望它运行的时间段内。 1 小于 23,所以 shouldrun=False。只有一个if (IF "%hour%" geq "02" SET "shouldrun=False" else SET "shouldrun=True") 应该会更好。 一天中的每个小时都是LEQ 23

标签: batch-file time command schedule hour


【解决方案1】:

试试这样:

@echo off & setlocal  ENABLEDELAYEDEXPANSION

::takes the current hour independent of the time format
for /f "usebackq tokens=* delims=" %%i in (`wmic os get LocalDateTime /value`) do for /f "tokens=* delims=" %%# in ("%%i") do set "%%#"
set "hour=%LocalDateTime:~6,2%"

::removes the leading zeroes
cmd /c exit /b %hour%
set hour=%errorlevel%

::checks if should run
if !hour! LEQ 23 if !hour! GEQ 2  (
        echo Outside Update Schedule
        EXIT /B 1
)

echo ---RUNNING----
::your code here. Second if is not needed.

【讨论】:

  • 您希望if !hour! LEQ 23 在什么时候返回 FALSE?
  • @Stephan - 你是对的,但我只是在遵循 OP 的逻辑。小时可以更改。未来。
  • 有效点。至少,这行得通。顺便说一句,删除前导零的好技巧。比set /a hour=1%hour%-100 慢,但在这里没关系。
【解决方案2】:

如果我要为此考虑,那么我会使用不同的类,这样我就不会遇到前导零的问题,也不需要 for 循环。

@%SystemRoot%\System32\wbem\WMIC.exe Path Win32_LocalTime Where "Hour < 2" | %SystemRoot%\System32\findstr.exe "\<0\> \<1\>" 1>NUL 2>&1 || Echo Exit /B 1
@Rem Your line(s) here

【讨论】:

    【解决方案3】:

    这似乎工作正常:

    @echo off
    SET hour=%time:~0,2%
    SET shouldrun=True
    
    IF %hour% GEQ 02 IF %hour% LEQ 19 SET shouldrun=False
    
    IF "%shouldrun%"=="False" (
            echo Outside Update Schedule
            EXIT /B 1
    )
    
    IF "%shouldrun%"=="True" (
            @TASKKILL /f /im some.exe > nul 2>&1
            @timeout /t 4 > nul
             - do things here -
            @timeout /t 2 > nul
            shutdown -r -f -y -t 2
            EXIT /B 0
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-07
      • 1970-01-01
      • 2011-02-18
      • 2013-04-30
      • 1970-01-01
      • 2010-10-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多