如何在指定的日期/时间运行bat文件?

时间:2012-06-13 17:02:01

标签: windows batch-file scheduler

我有一个bat文件,我希望在每个季度的特定日期/时间运行一年。 我是命令行的新手,我知道如何通过任务调度程序运行它,这很容易。

让我们说每个季度,第1个月和第2个月,我的bat文件应该在其他几周运行。一个季度的第三个月应该每周运行一次。可能的时间是凌晨6点,我该怎么办?请告诉我。感谢。

2 个答案:

答案 0 :(得分:3)

下面的批处理文件可以执行您想要的操作:

@echo off
rem Get the "monthInQuarter@weekInMonth" value of the last run:
set /P lastRun=< scheduler.txt
rem Get values from today date
for /F "tokens=1,2 delims=/" %%a in ("%date%") do (
   set /A "monthInQuarter=(1%%a-100)%%4, weekInMonth=(1%%b-101)/7+1, oddWeekInMonth=weekInMonth%%2"
)
if %weekInMonth% gtr 4 (
  set /A weekInMonth=4, oddWeekInMonth=0
)
set thisRun=%monthInQuarter%@%weekInMonth%
rem For 1st and 2nd month in each quarter:
if %monthInQuarter% leq 2 (
   rem For alternative weeks (1=yes, 2=no, 3=yes, 4=no):
   if %oddWeekInMonth% equ 1 (
      if "%thisRun%" neq "%lastRun%" (
         echo %thisRun%> scheduler.txt
         call :TheProcess
      )
   )
rem For the third month of a quarter:
) else if %monthInQuarter% equ 3 (
   rem Run it weekly:
   if "%thisRun%" neq "%lastRun%" (
      echo %thisRun%> scheduler.txt
      call :TheProcess
   )
)
exit

:TheProcess
rem Place here the desired process, ie:
echo This run only on selected weeks!
exit /B

此值表可能有助于理解调度逻辑:

month:          1 2 3 4 5 6 7 8 9 10 11 12
monthInQuarter: 1 2 3 0 1 2 3 0 1  2  3  0

day:            1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 ...
weekInMonth:    1 1 1 1 1 1 1 2 2  2  2  2  2  2  3  3  3  3  3 ...
oddWeekInMonth: 1 1 1 1 1 1 1 0 0  0  0  0  0  0  1  1  1  1  1 ...

注意:

  • 此批处理文件假设ECHO%DATE%命令以MM / DD / YYYY格式显示日期,如果月份或日期小于10,则左数为零。如果这不是您的区域设置日期格式,则略有需要修改。

  • 虽然可以修改此程序以使用任何日期格式,但我认为这不是一般用途文件,而是针对您的特定需求的特殊要求。

  • 此程序必须每天早上6:00通过任务计划程序运行。

  • 程序第一次运行“系统找不到指定的文件”。在创建辅助SCHEDULE.TXT文件之前出现消息。

我希望它有所帮助。

安东尼奥

PS - 我不认为这个问题可以通过vbs脚本或C#,JAVA等以更简单的方式解决......

答案 1 :(得分:2)

windows scheduler,但我怀疑你是否能够只使用Windows调度程序执行一个计划。

我要做的是用一些高级语言(C#,JAVA等)编写调度逻辑(例如,当你想要运行批处理文件时),然后在批处理文件的开头调用该程序来查看如果这是你关心的日期。

批处理文件可以设置为每天运行(或者如果需要,每天多次运行)使用Windows调度程序,但如果您的C#/ JAVA程序表明它是一个日期,它只会执行“真实的东西”你关心的。

相关问题