josep11
11/15/2014 - 6:07 PM

Know if a batch has been executed in the last X hours

Know if a batch has been executed in the last X hours

@echo off

pushd %~dp0
::sync
start /wait "" cmd /c cscript date.vbs
::async - debug
::start /b "" cscript date.vbs

if %errorlevel% EQU 0 (
	echo it's been less than 24 hours
	goto :eof
)

echo it's been more than 24 hours since last execution
::here we would execute the task
'################ name it date.vbs #################
Function Write(data, outFile)
	Set objFSO=CreateObject("Scripting.FileSystemObject")
	Set objFile = objFSO.CreateTextFile(outFile,True)
	objFile.Write data & vbCrLf
	objFile.Close
	
End Function

Function ReadDate()
	Set objFSO=CreateObject("Scripting.FileSystemObject")
	strFile="time.log"
	Set objFile = objFSO.OpenTextFile(strFile)
	Do Until objFile.AtEndOfStream
		strLine= objFile.ReadLine
		'Wscript.Echo strLine
	Loop
	objFile.Close
	ReadDate = strLine
End Function

Function HoursDiff(dt1, dt2) 
        If (isDate(dt1) And IsDate(dt2)) = false Then 
            TimeSpan = "00:00:00" 
            Exit Function 
        End If 

        HoursDiff = Abs(DateDiff("H", dt1, dt2)) 
End Function 

    oldDate = ReadDate() 'last Date
    d2 = Now() 
    
    h = HoursDiff(oldDate, d2) 
   
	Escriu d2, "time_last_try.log" 'we write the last try
  
If h < 24 Then 'change this if you want something
	Wscript.quit(0) 'retruns 0 if it has been executed the last 24 hours
Else
	Wscript.echo "writing new date"
	Write d2, "time.log"
	Wscript.quit(1) 'retruns 1 if it has been more than 24 hours since the last execution
End If