Solved

Batch file runs a process which hangs - how to restart automatically?

Posted on 2009-07-09
16
1,732 Views
Last Modified: 2012-05-07
I have a batch file that starts a VB script every day, it downloads reports and puts them onto a series of 'reportable' files and then sends them out.

Occasionally it gets stuck so I have to wait for an hour and then kill it manually and then restart. This one should be do-able as it runs as a service account, so all running processes by that user account can be killed but I don't know how to do this. I'd want it to
Ideally what it would do is query all processes (12 including cmd windows and java.exe) every few minutes and if no CPU was being used them terminate and start again.
The process also occasionally creates a .LCK file which would need to be removed as well for the process to restart. Any ideas?
0
Comment
Question by:davels
  • 6
  • 6
  • 4
16 Comments
 
LVL 16

Expert Comment

by:t0t0
ID: 24814900
you need to isolate the process which is causing the problem. Firstly, you say you kill all processes while not quite knowing which process is the actual process which does the filekeeping for you....

modify your batch file and put a PAUSE command directly prior to the application firing up then, do your query stuff to see which processes are already running THEN, run your process (as it appears in the batch file) and do another query - this should reveal what the applications process name is.

Re-edit you batch file and all is restiored.

You need to be certain you've narrowed your search down to the actual process that is causing your PC to 'hang'.... Are you sure there are no other commands in the batch file which could cause it this to happen?

If you remove the '@ECHO OFF' from the beginning of your batch file then each line of code is displayed on the screen as it is run. This may reveal where in you r batch file things are going amiss.

Merely killing processes is a drastic last resort.

It would help us to advise you further if we knew what application / process is causing the problem (and version number).

It would also be a great help in advising you if you could attach a copy of your batch file here for us to examine.

What version of windows are you running?
0
 
LVL 1

Author Comment

by:davels
ID: 24821163
Here is the initial code that is kicked off - if I run this script manually, it completes without fail every single time. This batch runs on a daily basis and it fails 3 days out of 5 most often.....
This one is start_services.bat
 

@ECHO OFF
 

REM **********************************************************************************************

REM *

REM * Name       : PCG_SCRIPT.BAT

REM *

REM * Description: Batch file to invoke the PC Gateway Services, download, and generate CSV file

REM *

**********************************************************************************************
 
 

CD /d E:\LIFFE\PC Gateway
 

REM Start the PC Gateway Services

ECHO Start the PC Gateway Services

rem PAUSE

cmd /c start_services.bat
 

REM Download yesterdays trade data

ECHO ""

ECHO Download yesterdays trade data

rem PAUSE

cmd /c download.bat /y
 

REM Generate Half Trade Database

ECHO Generate Half Trade Database

rem PAUSE

cmd /c gen_htd.bat /x=i /y
 

REM Create the reports listed in stasco_report_list.txt

cmd /c report.bat /y /v=Stasco_report_list.txt
 

REM Stop the PC Gateway Services

ECHO Stop the PC Gateway Services

rem PAUSE

cmd /c stop_services.bat

Open in new window

0
 
LVL 1

Author Comment

by:davels
ID: 24821165
This one is download.bat


REM Include any dependent jar files in the classpath
 

SET CLASSPATH=.
 

REM In development - use classes outside of PCGW jar in preference to jar

SET CLASSPATH=%CLASSPATH%;source
 

SET CLASSPATH=%CLASSPATH%;lib\debug.jar

SET CLASSPATH=%CLASSPATH%;lib\bjss.jar

SET CLASSPATH=%CLASSPATH%;lib\pcgw.jar

SET CLASSPATH=%CLASSPATH%;lib\jdom.jar

SET CLASSPATH=%CLASSPATH%;lib\jaxp.jar

SET CLASSPATH=%CLASSPATH%;lib\xerces.jar

SET CLASSPATH=%CLASSPATH%;lib\log4j.jar
 

SET POLICY_FILE=rmi.policy
 

REM Start the download application, passing through all command line args as is.
 

JAVA -Djava.security.policy=%POLICY_FILE% -cp %CLASSPATH% com.liffe.pcgw.cmdLines.Download %*

Open in new window

0
 
LVL 1

Author Comment

by:davels
ID: 24821169
This one is start_services.bat
REM Include any dependent jar files in the classpath
 

SET CLASSPATH=.
 

REM In development - use classes outside of PCGW jar in preference to jar

SET CLASSPATH=%CLASSPATH%;source
 

SET CLASSPATH=%CLASSPATH%;lib\debug.jar

SET CLASSPATH=%CLASSPATH%;lib\bjss.jar

SET CLASSPATH=%CLASSPATH%;lib\pcgw.jar

SET CLASSPATH=%CLASSPATH%;lib\jdom.jar

SET CLASSPATH=%CLASSPATH%;lib\jaxp.jar

SET CLASSPATH=%CLASSPATH%;lib\xerces.jar

SET CLASSPATH=%CLASSPATH%;lib\log4j.jar
 

SET POLICY_FILE=rmi.policy
 

REM Tidy up any old monitor files, as we will check which ones exist later to see if all services are running

JAVA -Djava.security.policy=%POLICY_FILE% -cp %CLASSPATH% com.liffe.pcgw.servicing.RemoveMonitorFiles
 

REM Start the PC Gateway Services
 

REM Start service manager first, since this will contain naming service and core services (event service)...

START JAVAW -Djava.security.policy=%POLICY_FILE% -cp %CLASSPATH% com.liffe.pcgw.servicing.ServiceManager %*
 

REM Give chance for core services to start, by forcing a wait, before STARTing bespoke services...

JAVA -Djava.security.policy=%POLICY_FILE% -cp %CLASSPATH% com.liffe.pcgw.servicing.EnsureCoreServicesRunning
 

REM Now for bespoke services...
 

START JAVAW -Djava.security.policy=%POLICY_FILE% -cp %CLASSPATH% com.liffe.pcgw.audit.AuditLogger %*

REM ... START JAVA -Djava.security.policy=%POLICY_FILE% -cp %CLASSPATH% com.liffe.pcgw.audit.AuditLogger /verbose %*
 

START JAVAW -Djava.security.policy=%POLICY_FILE% -cp %CLASSPATH% com.liffe.pcgw.fileGeneration.FileGeneratorServer %*

START JAVAW -Djava.security.policy=%POLICY_FILE% -cp %CLASSPATH% com.liffe.pcgw.housekeeping.FilePurgerServer %*

START JAVAW -Djava.security.policy=%POLICY_FILE% -cp %CLASSPATH% com.liffe.pcgw.flagFiles.FlagFileServer %*

START JAVAW -Xmx256m -Djava.security.policy=%POLICY_FILE% -cp %CLASSPATH% com.liffe.pcgw.Comms.GwComms %*
 

REM Monitor primary services as they start-up...

JAVA -Djava.security.policy=%POLICY_FILE% -cp %CLASSPATH% com.liffe.pcgw.servicing.EnsureCoreServicesRunning /a

Open in new window

0
 
LVL 1

Author Comment

by:davels
ID: 24821178
In the first script above - thats the one that kicks it all off - so just script.bat
0
 
LVL 16

Expert Comment

by:t0t0
ID: 24829301
I can't see anything immediately wrong with this. I've merged all 3 files into 1 file (below). Not sure if the CMD /C was necessary. Not sure what the java apps do and not sure if there's a need to set environment variables twice. Not sure what gen_htd.bat, report.bat nor stop_services.bat does.

Just wondering if adding /WAIT after some of the START commands is necessary or not,

You say the whole thing is kicked off every few minutes or so.... Hmmm.... I guess you must be sure the batch file process finishes so that services don't overlap. One way of achieving this is to use a sentinel value to prevent the batch file from running until a previous instance of itself ends.

In it's simplest form, you could add the line:

This line enables you to reset the sentinel file so that the batch file can be FORCED to run. This might be required if your batch file exits prematurely without properly reseting the sentinel file itself - this might happen if you CTRL-C out of your batch file for example, or one of your CALLED batch files fails to return to the main batch file for whatever reason.

   IF /I "%1"=="/reset" (
      DEL "%TEMP%\BatchProcess.Sentinel" 2>NUL
   )

The following will check for the existence of the sentinel file and if it does not exist then the batch file will create it and then continue to run as normal. If it does exist then the rest of the batch file will be skipped.

   IF EXIST "%TEMP%\BatchProcess.Sentinel" (
      EXIT /B 0
   ) ELSE (
      COPY NUL >"%TEMP%\BatchProcess.Sentinel"
   )

So, these should be placed immediately after the '@ECHO OFF' statement.

The last instruction in your batch file should be:

   DEL "%TEMP%\BatchProcess.Sentinel" 2>NUL

So, when the batch file completes it removes the sentinel file and indicates the batch process is complete. Now when scheduler runs your batch file every few moments, your batch file will first test to see if a previous instance of itself is already running.

The ONLY time you should run the batch file with the '/reset' command line option is when you run it manually (this won't effect the scheduled running of the batch file) however, this should only be done if you are certain the batch process has completed or was prematurely stopped.

See how you get on with that. If the scheduling of the batch processes is not the problem then we can do some logging to try to pinpoint what's going on inside your batch file - just a tip though, if you remove the '@ECHO OFF' from the start of all your batch files (associated with this batch process) then you'll see what commands are executing when the batch file is fired up by watching the DOS box.


@ECHO OFF
   IF /I "%1"=="/reset" (
      DEL "%TEMP%\BatchProcess.Sentinel" 2>NUL
   )

   IF EXIST "%TEMP%\BatchProcess.Sentinel" (
      EXIT /B 0
   ) ELSE (
      COPY NUL >"%TEMP%\BatchProcess.Sentinel"
   )

ECHO Start the PC Gateway Services
CD /d "E:\LIFFE\PC Gateway"

SET CLASSPATH=.
SET CLASSPATH=%CLASSPATH%;source
SET CLASSPATH=%CLASSPATH%;lib\debug.jar
SET CLASSPATH=%CLASSPATH%;lib\bjss.jar
SET CLASSPATH=%CLASSPATH%;lib\pcgw.jar
SET CLASSPATH=%CLASSPATH%;lib\jdom.jar
SET CLASSPATH=%CLASSPATH%;lib\jaxp.jar
SET CLASSPATH=%CLASSPATH%;lib\xerces.jar
SET CLASSPATH=%CLASSPATH%;lib\log4j.jar
SET POLICY_FILE=rmi.policy

START JAVA -Djava.security.policy=%POLICY_FILE% -cp %CLASSPATH% com.liffe.pcgw.servicing.RemoveMonitorFiles
START JAVAW -Djava.security.policy=%POLICY_FILE% -cp %CLASSPATH% com.liffe.pcgw.servicing.ServiceManager %*
JAVA -Djava.security.policy=%POLICY_FILE% -cp %CLASSPATH% com.liffe.pcgw.servicing.EnsureCoreServicesRunning
START JAVAW -Djava.security.policy=%POLICY_FILE% -cp %CLASSPATH% com.liffe.pcgw.audit.AuditLogger %*
START JAVAW -Djava.security.policy=%POLICY_FILE% -cp %CLASSPATH% com.liffe.pcgw.fileGeneration.FileGeneratorServer %*
START JAVAW -Djava.security.policy=%POLICY_FILE% -cp %CLASSPATH% com.liffe.pcgw.housekeeping.FilePurgerServer %*
START JAVAW -Djava.security.policy=%POLICY_FILE% -cp %CLASSPATH% com.liffe.pcgw.flagFiles.FlagFileServer %*
START JAVAW -Xmx256m -Djava.security.policy=%POLICY_FILE% -cp %CLASSPATH% com.liffe.pcgw.Comms.GwComms %*
JAVA -Djava.security.policy=%POLICY_FILE% -cp %CLASSPATH% com.liffe.pcgw.servicing.EnsureCoreServicesRunning /a

ECHO.
ECHO Download yesterdays trade data
JAVA -Djava.security.policy=%POLICY_FILE% -cp %CLASSPATH% com.liffe.pcgw.cmdLines.Download %*

ECHO Generate Half Trade Database
cmd /c gen_htd.bat /x=i /y
cmd /c report.bat /y /v=Stasco_report_list.txt

ECHO Stop the PC Gateway Services
cmd /c stop_services.bat

   DEL "%TEMP%\BatchProcess.Sentinel" 2>NUL
0
 
LVL 5

Expert Comment

by:Cumbrowski
ID: 24835783
You said that you execute a VBScript script which hangs from time to time.
I did not see the call of the script in your BATCH code.

Below is the code for a sample batch file that executes a VBScript with a TimeOut handler
It Tries to execute the VBSCRIPT script three times, giving it 10 minutes to execute each time
If it never completes, it will process another Error Handler where you need to specify what you want to do in those cases.
This is to prevent an indefinite loop of the batch where it tries to execute the VBScript again and again and never completes.

The VBScript is called using CSCRIPT.EXE versus WSCRIPT.EXE. The CSCRIPT command has a /T:nn option (TimeOut) where nn stands for the number of seconds the script has time to execute and complete.

Much better than this would be the implementation of error and timeout handling within the VBScript code itself.
If you don't know what causes the script to hang, then you should first try to isolate the problem.
You can create individual VBScript scripts for each of the tasks that the main script performs or you could write to a log file at specific times in your main script to see which steps were finished and how long each step took. I can provide you with some template code for writing a log file, which is easy to use like:

 Call WriteLog "Custom Message"

I will add the VBS code to another comment.
@ECHO OFF

CLS

REM --------------------------------------------------------

REM SAMPLE BATCH FOR VBSCRIPT EXECUTION and TIMEOUT HANDLING

REM --------------------------------------------------------

Setlocal enabledelayedexpansion

SET MaxNumExec=3

SET NumExec=0

CALL :STARTSCRIPT

GOTO :EOF
 

:STARTSCRIPT

set /a NumExec+=1

CSCRIPT.EXE /NOLOGO /B /T:600 "DRIVE:\PATH\SCRIPTNAME.VBS" "ARGUMENT1" "ARGUMENT2"

IF NOT "%errorlevel%"=="0" (

  IF "%NumExec%"=="%MaxNumExec%" GOTO :ErrorHandler

  GOTO :STARTSCRIPT

) 

GOTO :EOF
 

:ErrorHandler

REM Script was called the maximum number of times and never completed successfully

REM Do Whatever you need to do in this Case, such as

REM - write something to an Error Log

REM - write a message to the Windows Event Log

REM - Send a NET SEND message to your admin console

REM - Run an Alert Script that sends an email 

REM Etc.

GOTO :EOF

Open in new window

0
 
LVL 5

Expert Comment

by:Cumbrowski
ID: 24835866
Below is the code for a generic Write Log File Function in VBScript, which comes in handy for logging and trouble-shooting

Notes:

If the Log File was not open yet (first call of the function), it will open the log file or create a new one, if the file does not exist yet and write some general information about the current script execution to the log like.

- Script Name
- Script Path
- All Script Call Command Line Arguments
- Work Path
- WScript Version
- Script Host (WSCRIPT or CSCRIPT)
- User Name who Executed the Script
- Computer Name where the Script was executed


Each log file entry has the current date/time automatically included in the format YYYY-MM-DD HH:MM:SS

'Global Constants and Variables (Add to Beginning of the Main Script)

Const ForAppending = 8, ForReading = 1, ForWriting = 2

Dim objFSO: Set objFSO = CreateObject("Scripting.FileSystemObject")

Dim objWSHNetWork: Set objWSHNetWork = CreateObject("WScript.NetWork")

Dim objCmdlineArguments: Set objCmdlineArguments = Wscript.arguments

Dim objLogFile, strLogFile
 

'---------------------------------------------------------

'Specify Path and File Name of the Log File

'The Example below writes a log file in the directory from where the script was called 

'with the file name "SCRIPTLOG.TXT"

'--------------------------------------------------------

strLogFile = objFSO.BuildPath(objFSO.GetAbsolutePathName("."),"SCRIPTLOG.TXT")
 
 

'Within anywhere else of your code use

Call WriteLog "Custom Message" 
 
 
 
 
 

'========================================================================

'Write Log File Functions/Subs

'========================================================================

Sub WriteLog(sLocErrLogMsg)

'-----------------------------------------------

'Input: String (Single Line to write to Log File)

'Output: None

'-----------------------------------------------

'Requires Global Objects:

'   objFSO, objWSHNetWork, objLogFile, objCmdlineArguments

'Requires Global Constants and Variables:

'   ForWriting, strLogFile

'Calls Additional Global Sub or Function:

'   fnLogDateFormat

'-----------------------------------------------
 

  Dim bLocOpenLog: bLocOpenLog = false

  Dim sLocFullErrMsg, sLocArgument
 

     if not isObject(objLogfile) then

      set objLogfile = nothing

    end if
 

    if not (objLogfile is nothing) then

    else

        bLocOpenLog = true

    end if
 

     if  bLocOpenLog = true then

       Set objLogfile = objFSO.OpenTextFile(strLogFile, ForWriting, True,-2)

       WriteLog "----------------------------------------------"

       WriteLog "New Log Started"

			 WriteLog "Script Name: " & Wscript.ScriptName

			 WriteLog "Script Path: " & left(Wscript.ScriptFullName, _

			                 len(Wscript.ScriptFullName) - len(Wscript.ScriptName) - 1)

			 if objCmdlineArguments.Unnamed.Count = 0 then

          WriteLog "No Unnamed Command Line Arguments"

			 else

    			WriteLog "Unnamed Script Arguments:"

          For Each sLocArgument in objCmdlineArguments.Unnamed

					    WriteLog " " & chr(62) & sLocArgument & chr(60)

          Next											 

       end if
 

			 if objCmdlineArguments.Named.Count = 0 then

          WriteLog "No Named Command Line Arguments"

			 else

    		 WriteLog "Named Script Arguments:"

  			 For each sLocArgument in objCmdlineArguments.Named

    				 WriteLog " " & sLocArgument & chr(62) & _

						                  objCmdlineArguments.Named.Item(sLocArgument) & chr(60)

  			 Next

       End if

       WriteLog "Work Path: " & strGlobWorkPath

       WriteLog "----------------------------------------------"

       WriteLog "Wscript Version: " &  Wscript.Version

       WriteLog "Script Host: " & Wscript.FullName

       WriteLog "User Name: " & objWSHNetWork.UserName

       WriteLog "Computer: " & objWSHNetWork.ComputerName

       WriteLog "-----------------------------------------------"

     end if
 

     sLocFullErrMsg = fnIncLogDateFormat(now) & chr(9) & sLocErrLogMsg

     objLogFile.Writeline sLocFullErrMsg
 

end Sub

'----------------------------------------------------------------------

Function fnIncLogDateFormat(dLocSourceDate)

'-----------------------------------------------

'Input: Date/Time

'Output: String (Format: YYYY-MM-DD_HH:NN:SS)

'-----------------------------------------------

  Const sLocLogDtNumbers = "0000"

  Dim sLocLgDtYYYY, sLocLgDtMM, sLocLgDtDD, sLocLgDtHH, sLocLgDtNN, sLocLgDtSS
 

  sLocLgDtYYYY = right(sLocLogDtNumbers & year(dLocSourceDate),4)

  sLocLgDtMM = right(sLocLogDtNumbers & month(dLocSourceDate),2)

  sLocLgDtDD = right(sLocLogDtNumbers & day(dLocSourceDate),2)

  sLocLgDtHH = right(sLocLogDtNumbers & hour(dLocSourceDate),2)

  sLocLgDtNN = right(sLocLogDtNumbers & minute(dLocSourceDate),2)

  sLocLgDtSS = right(sLocLogDtNumbers & second(dLocSourceDate),2)

  fnIncLogDateFormat = sLocLgDtYYYY & "-" & sLocLgDtMM & "-" & sLocLgDtDD & _

                 " " & sLocLgDtHH & ":" & sLocLgDtNN & ":" & sLocLgDtSS

End Function

'----------------------------------------------------------------------

Open in new window

0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 16

Expert Comment

by:t0t0
ID: 24835930
Cumbrowski

As you are aware. I have attended to the asker. Rather than confuse him by chucking more code at him, it might be wiser to try one thing at a time. In this case, I have given instructions on how to implement exclusive scheduling of his batch process. It would be wiser to wait for feedback from the asker before suggesting other avenues to explore.

We have already discussed isolating the problem and this is something that is on-going.

Personally, I suspect the problem is due to another instance of the process starting before the previous instance has ended. This certainly would cause undesirable effects. What leads me to suspect this is that the asker states his scheduler fires up his batch process every few minutes or whatever...

It is vital this is ruled out before continuing further. I realise it's the weekend therefore, I do not anticipate hearing back from the asker until at least during the first working week day.

I really don't mind you chipping in however, I hope this does not confuse the asker.

In the time it has taken me to write this reply, you have added yet another comment. I cannot see the point in bo=mbarding the asker with vb code when he himself has supplied a batch file as the possible source of his problem.
0
 
LVL 5

Expert Comment

by:Cumbrowski
ID: 24836647
T0t0

I did not intend to "chip in", but to assist you.
It seemed to me that the problem was approached from the wrong direction.

The batch that hangs appears to be just a symptom of the problem, but not the cause. You already mentioned something in that regards in your comments, but did not follow up on it.

Adding logging to the VBScript (where the asker did not post the code) is probably the best thing to do in order to determine what hangs where and why. My code could help with this and assist in finding the best solution for the actual problem.

The first code example follows the same idea, but one step further in the process, in case that the executed script cannot be modified.
Cheers!
0
 
LVL 1

Author Comment

by:davels
ID: 24837940
OK... so here is some clarity.

Scenario 1) A scheduled task runs the attached code which does tend to fail more often than not

Scendario 2) I run the above batch files which always works but is a manual process and must be watched


'==========================================================================

'

' VBScript Source File - PCGW.vbs

'

' NAME: PCG Downloader/Mailer

'

'

'==========================================================================

'Option Explicit
 

'==========================================================================

' Global declarations

'==========================================================================

' Location where CSV files are stored

strCSVFilePath = "E:\LIFFE\PC Gateway\I\Db\"
 

' Location where CSV files are archived To

strCSVArchivePath = "E:\LIFFE\PCGATEWAY_CSV_FILES\"
 

' Location where report files are stored

strReportFilePath = "E:\LIFFE\PC Gateway\I\Reports\"
 

' Location where zip files are stored

strZipFilePath = "E:\LIFFE\PCGATEWAY_ZIP_FILES\"
 

' Path to PCGateway start script

strPCGWPath = "E:\LIFFE\PC Gateway\Stasco_script.bat"

'strPCGWPath = "E:\test.bat"
 

' Path to Winzip

strWinzipPath = "C:\Program Files\WinZip\"
 

' Email from address

strEmailSender = "PCGateway@STLONS0034"
 

' Email recipients

strEmailRecipients = "blanked out"
 
 

' Support contacts

strSupportContacts = "Email: GX TR STSS WINTEL EU"
 

' Support email

strSupportEmail = "blah@blah.com"
 

' Create a file system object that we'll use for various checking, etc

Set objFileSystemObject = CreateObject("Scripting.FileSystemObject")
 

' Create a Shell object that will be used for launching processes later

Set objShell = WScript.CreateObject("WScript.Shell")
 

'==========================================================================

' Functions

'==========================================================================

' Sends a message using SMTP (and CDO)

Function Sendmail(strSenderAddr, strRecipientAddr, strMessSubject, strMessContent, strAttachmentPath)

	Dim objMessage

	Set objMessage = CreateObject("CDO.Message")

	objMessage.Subject = strMessSubject

	objMessage.From = strSenderAddr 

	objMessage.To = strRecipientAddr 

	objMessage.HTMLBody = strMessContent

	If strAttachmentPath <> "" Then objMessage.AddAttachment strAttachmentPath

	objMessage.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2

	objMessage.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "146.194.8.162" 

	objMessage.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25 

	objMessage.Configuration.Fields.Update

	objMessage.Send

End Function
 

'==========================================================================

' Main script starts here

'==========================================================================

' Send a mail saying we've started

Sendmail strEmailSender, strEmailRecipients, "PC Gateway has started at " & Now, "<font face=""arial""><b>The PC-Gateway process has started.</b><p>Please allow 60 mins for the process to complete and for the CSV file to be sent.</p><p>If you do not receive the CSV file after 60 mins please click <a href=""mailto:" & strSupportEmail & """>here</a> to contact support or call " & strSupportContacts & ".</p>", ""
 

' Run the PCGateway Script

objShell.Run """" & strPCGWPath & """", 0, True
 

' Get a list of files in the CSV folder

Set objFolder = objFileSystemObject.GetFolder(strCSVFilePath)

Set objFileCollection = objFolder.Files
 

'Check if there are any CSV files in the CSVFilePath

If objFileCollection.Count > 0 Then

	' We have some files in there - loop through each file ending in CSV and check if the

	' size is greater than 0 - count legitimate CSV files

	intFileCounter = 0

	For Each strFilename In objFileCollection

		If Right(UCase(strFilename), 3) = "CSV" Then

			Set objFile = objFileSystemObject.GetFile(strFilename)

			If objFile.Size = 0 Then

				objFile.Delete

			Else

				intFileCounter = intFileCounter + 1

				strCSVFilename = strFilename.Name

			End If

		End If

	Next
 

	' We should just have 1 file . . .

	If intFileCounter = 1 Then

		' Check the files in the report folder exist

		' Get a list of files in the report folder

		Set objReportFolder = objFileSystemObject.GetFolder(strReportFilePath)

		Set objReportFileCollection = objReportFolder.Files

		

		If objReportFileCollection.Count > 0 Then

			' There are some report files - construct the zip file name

			strZipFilename = Left(strCSVFilename, Len(strCSVFilename) - 4) & ".zip"
 

			' Check the file doesn't exist already

			If Not objFileSystemObject.FileExists(strZipFilePath & strZipFilename) Then

				' Zip file doesn't exist, create and add files

				objShell.Run """" & strWinzipPath & "wzzip.exe"" " & """" & strZipFilePath & strZipFilename & """ """ & strReportFilePath & "*.dat"" """ & strCSVFilePath & "*.csv""", 0, True
 

				' Send email with attachment

				Sendmail strEmailSender, strEmailRecipients, "PC Gateway has finished at " & Now, "<font face=""arial""><b>The PC-Gateway process has now finished.</b><p>Please find the half trade database and report files in the attached zip file (" & strZipFilename & ").<p><b>Please note that the attached files are confidential in nature.</b><p>Click <a href=""mailto:" & strSupportEmail & """>here</a> to contact support or call " & strSupportContacts & ".", strZipFilePath & strZipFilename

				

				' Delete *.DAT from the report files folder

				Set objFolder = objFileSystemObject.GetFolder(strReportFilePath)

				Set objFileCollection = objFolder.Files
 

				For Each strFilename In objFileCollection

					If Right(UCase(strFilename), 3) = "DAT" Then

						Set objFile = objFileSystemObject.GetFile(strFilename)

						objFile.Delete

					End If

				Next

				

				' Archive the CSV file

				Set objFile = objFileSystemObject.GetFile(strCSVFilePath & strCSVFilename)

				objFile.Move(strCSVArchivePath)

			Else

				' Zip file exists - send email

				Sendmail strEmailSender, strEmailRecipients, "PC Gateway Error - Zip file already exists!", "<font face=""arial""><b>The PC-Gateway process has encountered a problem.</b><p>Please click <a href=""mailto:" & strSupportEmail & """>here</a> to contact support or call " & strSupportContacts & ".</p>", ""

				WScript.Echo "Zip file exists!"

			End If

		Else

			' Report files don't exist - send email

			Sendmail strEmailSender, strEmailRecipients, "PC Gateway Error - Report files don't exist!", "<font face=""arial""><b>The PC-Gateway process has encountered a problem.</b><p>Please click <a href=""mailto:" & strSupportEmail & """>here</a> to contact support or call " & strSupportContacts & ".</p>", ""

			WScript.Echo "Report files don't exist!"

		End If

	Else

		' More than one CSV file exists - send email

		Sendmail strEmailSender, strEmailRecipients, "PC Gateway Error - More than one CSV file exists!", "<font face=""arial""><b>The PC-Gateway process has encountered a problem.</b><p>Please click <a href=""mailto:" & strSupportEmail & """>here</a> to contact support or call " & strSupportContacts & ".</p>", ""

		WScript.Echo "More than one CSV file exists!"

	End If

Else

	' No CSV files exist - send email

	Sendmail strEmailSender, strEmailRecipients, "PC Gateway Error - No CSV files exist!", "<font face=""arial""><b>The PC-Gateway process has encountered a problem.</b><p>Please click <a href=""mailto:" & strSupportEmail & """>here</a> to contact support or call " & strSupportContacts & ".</p>", ""

	WScript.Echo "No CSV files exist!"

End If

Open in new window

0
 
LVL 16

Expert Comment

by:t0t0
ID: 24838240
cumbrowski

>> "It seemed to me that the problem was approached from the wrong direction"

I disagree entirely. As I stated in my previous post, we must first eliminate the possibility of multiple instances of the batch process executing at the same time based on information gathered from the asker.

>> "The batch that hangs appears to be just a symptom of the problem"

Yes, I am aware of that which is why I want to be certain the batch process is given the enough time to complete before restarting the same batch process again. The reason is due to the fact we do not know what the asker's other processes do - mostly in terms of opening and closing files and possible share issues.

I fulkly agree that logging batch process activity will reveal where the batch process stalls, and this is the area I would like to explore next.

In the time it has taken me to reply, I notice the asker has just posted another comment. Until I review that comment I cannot procede further with this current reply....
0
 
LVL 1

Author Comment

by:davels
ID: 24933017
Any update on this please? Thanks
0
 
LVL 16

Expert Comment

by:t0t0
ID: 24933113
In an earlier post I stated:

>>"If you remove the '@ECHO OFF' from the beginning of your batch file then each line of code is displayed on the screen as it is run. This may reveal where in your batch file things are going amiss"

Did you try this? If so, at what point was your batch file either labouring or hanging?

Also, at what intervals is scheduler set to run your batch file?



0
 
LVL 5

Accepted Solution

by:
Cumbrowski earned 500 total points
ID: 24974610
To the VBScript.

The check if the file is > 0 might not be sufficient to assume that the file is not currently in use (written to the server).  You might want to check for each CSV file that it is not in use by another process.

How to do that can be found here
http://www.experts-exchange.com/Programming/Languages/Visual_Basic/VB_Script/Q_23190324.html

I don't believe that any of the files that you try to move could be in read-only status, but if that is the case, it could cause problems as well. Below is a sub routine that checks if the read-only flag is set for a file and removes it. You might want to comment out the "On Error Resume Next" for the first run, because I did not verify the code. I used the code from a script of mine and changed some variables etc. You would not catch If I made a typo, if the On Error Resume Next is on.

In addition to that does it not hurt to implement the logging routine that I posted. It will help with the trouble shooting, if there is another issue beyond the ones that I covered in this comment.




'Usage

'RemoveReadOnlyAttribute sFileNameAndPath

'

'Requires objFileSystemObject to be created

'Set objFileSystemObject = CreateObject("Scripting.FileSystemObject")

'
 

Sub RemoveReadOnlyAttribute(sFileName)

Dim oFile, LoopCounter, bteFileAttributes

'Remove Read-Only Attribute (if set)

  On Error Resume next

  Set oFile = objFileSystemObject.GetFile(sFileName)

  bteFileAttributes = oFile.Attributes

  For LoopCounter = 7 to 0 Step - 1

   'Read all Attributes to keep it general

   If (bteFileAttributes-2^LoopCounter) >= 0 then

   'Flag is Set

     if LoopCounter = 0 then

     'its the Read Only Flag

	oFile.Attributes = oFile.Attributes - 1

     end if

     bteFileAttributes = bteFileAttributes-2^LoopCounter

   end if

  Next

  Set oFile = Nothing

  On Error Goto 0

End Sub

Open in new window

0
 
LVL 16

Expert Comment

by:t0t0
ID: 25277338
davels

Please close this question.

Thank you.
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

The following is a collection of cases for strange behaviour when using advanced techniques in DOS batch files. You should have some basic experience in batch "programming", as I'm assuming some knowledge and not further explain the basics. For some…
I have published numerous articles here at Experts Exchange that present programs/scripts written in a language called AutoHotkey. Each of those articles has a brief paragraph describing where to download the product and how to install it. I have al…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now