views:

541

answers:

3

I would like to write a windows batch file for the purpose of renaming a file every 25 seconds. I would also like the batch file to terminate after 300 seconds have passed. How would I go about doing this? Here is what I have thusfar.

START

RENAME test.g test.go

SLEEP 25

RENAME test.go test.g

GOTO START
+1  A: 

you will need the sleep command, you can download it here.

then you can do something like this:

echo this is a test > test.txt
SET x=
:START
CALL SET /a x = %x% +1
rename test.* test.%x%

CALL SET /a y = %x% * 25

IF '%x%' == '300' GOTO END

CALL SLEEP 25
GOTO START

:END
akf
+3  A: 

Well, this is not too difficult. There are a bunch of well-known batch tricks, such as mis-using ping to sleep (which saves you from having to integrate a non-standard tool) and we can then come up with the following:

@echo off
setlocal
set n=0
:start
ren test.g test.go
ping localhost -n 26>nul 2>&1
ren test.go test.g
set /a n+=25
if %n% LSS 300 goto start
endlocal

setlocal and endlocal will ensure that all environment variables we create and modify will remain only in scope of the batch file itself. The command

ping localhost -n 26 >nul 2>&1

will wait 25 seconds (because the first ping will be immediate and every subsequent one incurs a one-second delay) while throwing away all normal and error output (>nul 2>&1).

Finally we are keeping track of how long we waited so far in the %n% variable and only if n is still below 300 we continue looping. You might as well do it with a for loop, though:

@echo off
setlocal
set n=300
set /a k=n/25
for /l %%i in (1,1,%k%) do (
    ren test.g test.go
    ping localhost -n 26>nul 2>&1
    ren test.go test.g
)
endlocal

which will first calculate how often it would need to loop and then just iterate the calculated number of times.

Joey
A: 

if you are using windows, then i assume you can use vbscript.

Set objFS = CreateObject("Scripting.FileSystemObject")
strFile1 = "file.txt"
strFile2 = "new.txt"
While 1=1
    Set objFile1 = objFS.GetFile(strFile1)
    objFile1.Name = strFile2
    Set objFile1 = Nothing
    WScript.Echo "sleeping.."
    WScript.Sleep (25 * 60)
    Set objFile2 = objFS.GetFile(strFile2)
    objFile2.Name = strFile1
    Set objFile2 = Nothing
    WScript.Sleep (300 * 60)
Wend

save the above as myscript.vbs and on command line

c:\test> cscript /nologo myscript.vbs
ghostdog74