@echo off setlocal set MAX_CONCURRENT=3 set /a currentCount=0 :StartBatchLoop :: Count…
- User
@echo off setlocal
set MAX_CONCURRENT=3 set /a currentCount=0
:StartBatchLoop :: Count how many semaphore files are created set /a currentCount=0 for /f %%i in ('dir /b "C:\path\to\semaphore*.sem" 2^>nul ^| find /c /v ""') do set currentCount=%%i
:: If we have reached the maximum, wait and check again if %currentCount% geq %MAX_CONCURRENT% ( timeout /t 1 >nul goto StartBatchLoop )
:: Create a semaphore file echo. > "C:\path\to\semaphore\process.semaphore"
:: Run your batch file in the background start /b cmd /c "C:\path\to\your\batchfile.bat"
:: Wait for the batch file to finish and then delete the semaphore file :WaitForBatch timeout /t 1 >nul if exist "C:\path\to\semaphore\process.semaphore" ( goto WaitForBatch ) del "C:\path\to\semaphore\process.semaphore"
:: Go back to start the next batch file goto StartBatchLoop
i need to work on file read target office_id (id.txt) then ping to that id if online then do something
- Assistant
To expand your batch script to read from a file that contains a list of
office_ids (assuming eachoffice_idis on a separate line inid.txt), ping eachoffice_id, and if it's online, perform a certain operation, you can modify your script as follows. Below is a complete batch file script including these additional functionalities:@echo off setlocal set MAX_CONCURRENT=3 set /a currentCount=0 :StartBatchLoop :: Count how many semaphore files are created set /a currentCount=0 for /f %%i in ('dir /b "C:\path\to\semaphore\*.sem" 2^>nul ^| find /c /v ""') do set currentCount=%%i :: If we have reached the maximum, wait and check again if %currentCount% geq %MAX_CONCURRENT% ( timeout /t 1 >nul goto StartBatchLoop ) :: Read the office_ids from id.txt for /f "usebackq delims=" %%a in ("C:\path\to\id.txt") do ( set "office_id=%%a" :: Create semaphore file for the current office_id echo. > "C:\path\to\semaphore\process_%%a.semaphore" :: Ping the office_id (assumed to be an IP address or hostname) ping -n 1 %%a >nul if errorlevel 1 ( echo %%a is offline, skipping... del "C:\path\to\semaphore\process_%%a.semaphore" >nul 2>&1 goto EndOfficeIdIteration ) else ( echo %%a is online, performing operations... :: Run your batch file in the background start /b cmd /c "C:\path\to\your\batchfile.bat %%a" ) :: Wait for the batch file to finish :WaitForBatch timeout /t 1 >nul if exist "C:\path\to\semaphore\process_%%a.semaphore" ( goto WaitForBatch ) del "C:\path\to\semaphore\process_%%a.semaphore" :EndOfficeIdIteration ) :: Go back to start the next batch file goto StartBatchLoopExplanation:
-
Reading from
id.txt: The script reads each line fromid.txtwhich contains theoffice_ids. It uses "usebackq" to allow spaces in the path and "delims=" to read the entire line. -
Creating Semaphore File: It creates a unique semaphore file for each
office_id, namedprocess_<office_id>.semaphore. -
Ping Command: It pings the
office_id. If the ping fails (the office_id is offline), it deletes the semaphore file and skips to the nextoffice_id. -
Running Batch File: If the
office_idis online, the script starts the specified batch file (your\batchfile.bat) in the background, passing theoffice_idas an argument. You might need to adjust yourbatchfile.batto take this argument for whatever processing you want to do. -
Semaphore Management: After launching the process, it waits for the semaphore file to be deleted by the other batch file, indicating that the operation has completed.
-
Looping: Finally, it goes back to the start to check for more semaphore files.
Note:
- Ensure the paths used in the script match your system's configuration.
- Adjust the path to
id.txt, your semaphore files, and the batch file accordingly. - This script assumes that the
office_idcorresponds to valid IP addresses or host names. Modify the logic if you have different requirements.
-
- User
make summary in main bat which is on going work
- Assistant
Certainly! If you want to keep track of a summary of ongoing work in your batch script, you can modify the batch file to log the status of each operation to a summary file. This summary file can include information like the
office_id, the status (online/offline), and possibly start and end times of processing for each ID.Here's how to incorporate a summary logging feature into your existing batch script:
@echo off setlocal set MAX_CONCURRENT=3 set /a currentCount=0 set "summaryFile=C:\path\to\summary.log" :: Initialize or clear the summary log echo Summary of ongoing work > "%summaryFile%" echo ======================= >> "%summaryFile%" echo. >> "%summaryFile%" :StartBatchLoop :: Count how many semaphore files are created set /a currentCount=0 for /f %%i in ('dir /b "C:\path\to\semaphore\*.sem" 2^>nul ^| find /c /v ""') do set currentCount=%%i :: If we have reached the maximum, wait and check again if %currentCount% geq %MAX_CONCURRENT% ( timeout /t 1 >nul goto StartBatchLoop ) :: Read the office_ids from id.txt for /f "usebackq delims=" %%a in ("C:\path\to\id.txt") do ( set "office_id=%%a" :: Create semaphore file for the current office_id echo. > "C:\path\to\semaphore\process_%%a.semaphore" :: Ping the office_id (assumed to be an IP address or hostname) ping -n 1 %%a >nul if errorlevel 1 ( echo %%a is offline, skipping... echo %%a is offline >> "%summaryFile%" del "C:\path\to\semaphore\process_%%a.semaphore" >nul 2>&1 goto EndOfficeIdIteration ) else ( echo %%a is online, performing operations... echo %%a is online >> "%summaryFile%" :: Note the start time echo Processing %%a started at %time% >> "%summaryFile%" :: Run your batch file in the background start /b cmd /c "C:\path\to\your\batchfile.bat %%a" ) :: Wait for the batch file to finish :WaitForBatch timeout /t 1 >nul if exist "C:\path\to\semaphore\process_%%a.semaphore" ( goto WaitForBatch ) :: Simulation of processing time (Delete or comment this line in actual use) timeout /t 1 >nul :: Log the end time echo Processing %%a finished at %time% >> "%summaryFile%" del "C:\path\to\semaphore\process_%%a.semaphore" :EndOfficeIdIteration ) :: Go back to start the next batch file goto StartBatchLoopSummary Feature Explanation:
-
Summary File Initialization: The script creates or clears a summary log file (
summary.log) when it starts. This log will store information about each operation executed in the loop. -
Logging Status: When the script pings each
office_id, it logs whether the ID is online or offline into the summary file. -
Start and End Time Logging: Each time a new
office_idis processed, the script logs the start and end times of processing for that ID. This provides a timeline of when each operation begins and finishes. -
Comment Out Duration Simulation: To simulate processing, there's an added timeout that you'd probably want to replace with actual processing logic in a real-world scenario. You may want to comment it out or adjust it as needed.
Note:
- Ensure that the paths used in the script match your configuration.
- Customize the content of
batchfile.batand what operations are performed as per your requirements. - The summary log will be appended with information for each processed
office_id, allowing you to track ongoing work efficiently.
-
- User
can make type command on main bat to show
- Assistant
To add a command in your batch file that displays the contents of the summary log on the console (or command prompt) while the script is running, you can use the
typecommand. This will allow you to see the summary of ongoing work in real-time. You can place thetypecommand at appropriate places in your script to display the summary after eachoffice_idis processed.Here’s the modified batch script with the
typecommand included:@echo off setlocal set MAX_CONCURRENT=3 set /a currentCount=0 set "summaryFile=C:\path\to\summary.log" :: Initialize or clear the summary log echo Summary of ongoing work > "%summaryFile%" echo ======================= >> "%summaryFile%" echo. >> "%summaryFile%" :StartBatchLoop :: Count how many semaphore files are created set /a currentCount=0 for /f %%i in ('dir /b "C:\path\to\semaphore\*.sem" 2^>nul ^| find /c /v ""') do set currentCount=%%i :: If we have reached the maximum, wait and check again if %currentCount% geq %MAX_CONCURRENT% ( timeout /t 1 >nul goto StartBatchLoop ) :: Read the office_ids from id.txt for /f "usebackq delims=" %%a in ("C:\path\to\id.txt") do ( set "office_id=%%a" :: Create semaphore file for the current office_id echo. > "C:\path\to\semaphore\process_%%a.semaphore" :: Ping the office_id (assumed to be an IP address or hostname) ping -n 1 %%a >nul if errorlevel 1 ( echo %%a is offline, skipping... echo %%a is offline >> "%summaryFile%" del "C:\path\to\semaphore\process_%%a.semaphore" >nul 2>&1 goto EndOfficeIdIteration ) else ( echo %%a is online, performing operations... echo %%a is online >> "%summaryFile%" :: Note the start time echo Processing %%a started at %time% >> "%summaryFile%" :: Run your batch file in the background start /b cmd /c "C:\path\to\your\batchfile.bat %%a" ) :: Wait for the batch file to finish :WaitForBatch timeout /t 1 >nul if exist "C:\path\to\semaphore\process_%%a.semaphore" ( goto WaitForBatch ) :: Simulation of processing time (Delete or comment this line in actual use) timeout /t 1 >nul :: Log the end time echo Processing %%a finished at %time% >> "%summaryFile%" :: Display the current summary log echo. echo Current Summary Log: type "%summaryFile%" echo. del "C:\path\to\semaphore\process_%%a.semaphore" :EndOfficeIdIteration ) :: Go back to start the next batch file goto StartBatchLoopKey Modifications:
-
Displaying the Summary: After logging the finish time of processing for each
office_id, the script executes thetypecommand to read the contents ofsummary.logand display it in the console. This allows you to see the cumulative status of the operations performed so far. -
Separation for Readability: I've added
echo.commands before and after thetypecommand for better readability in the console output.
Note:
- Make sure the paths to
summary.logandid.txtare properly set according to your environment. - This way, as each
office_idis processed, you'll get a real-time view of what's happening in your batch script, making tracking easier. - This could create a lot of output if there are many
office_ids, so consider how frequently you need this information displayed. You might decide to show the summary less frequently in a more extensive implementation.
-
- User
@echo off setlocal
set MAX_CONCURRENT=3 set /a currentCount=0 set "summaryFile=log\summary.log"
:: Initialize or clear the summary log echo Summary of ongoing work > "%summaryFile%" echo ======================= >> "%summaryFile%" echo. >> "%summaryFile%"
:StartBatchLoop :: Count how many semaphore files are created set /a currentCount=0 for /f %%i in ('dir /b "log\semaphore*.sem" 2^>nul ^| find /c /v ""') do set currentCount=%%i
:: If we have reached the maximum, wait and check again if %currentCount% geq %MAX_CONCURRENT% ( timeout /t 1 >nul goto StartBatchLoop )
:: Read the office_ids from id.txt for /f "usebackq delims=" %%a in ("st.txt") do ( set "store_id=%%a" set "serv_id=PTH%%a" :: Create semaphore file for the current office_id echo. > "log\semaphore\process_%%a.semaphore"
:: Ping the office_id (assumed to be an IP address or hostname) ping -n 1 !serv_id! -w 1000 >nul if errorlevel 1 ( echo %%a is offline, skipping... echo %%a is offline >> "%summaryFile%" del "log\semaphore\process_%%a.semaphore" >nul 2>&1 goto EndOfficeIdIteration ) else ( echo %%a is online, performing operations... echo %%a is online >> "%summaryFile%" :: Note the start time echo Processing %%a started at %time% >> "%summaryFile%" :: Run your batch file in the background start /b cmd /c "C:\path\to\your\batchfile.bat %%a" ) :: Wait for the batch file to finish :WaitForBatch timeout /t 1 >nul if exist "log\semaphore\process_%%a.semaphore" ( goto WaitForBatch ) :: Simulation of processing time (Delete or comment this line in actual use) timeout /t 1 >nul :: Log the end time echo Processing %%a finished at %time% >> "%summaryFile%" :: Display the current summary log echo. echo Current Summary Log: type "%summaryFile%" echo. del "log\semaphore\process_%%a.semaphore" :EndOfficeIdIteration)
:: Go back to start the next batch file goto StartBatchLoop
check it again
- Assistant
The batch script you provided is overall structured well, but there are a few details to check and improve for it to function correctly and smoothly. Here are a few points to consider:
-
Delayed Expansion: Since you're using variables that are set inside a loop, such as
store_idandserv_id, you should use delayed variable expansion (!variable!) instead of normal expansion (%variable%) to access those values. This will ensure that you can access the values as they are updated within the loop. -
Ping Command Handling: The way you're pinging the
serv_idneeds to ensure thatPTH%%acorrectly evaluates to a valid hostname or IP address. -
Wait Condition: The script should handle waiting for the background process without assuming
.semaphorefiles will only be deleted once the batch completes. -
Error Handling and Cleanup: It's always good practice to ensure that any semaphore files that should be removed are handled correctly, even in failure cases.
-
Direct Paths: Be careful with paths. Ensure your path to
batchfile.batis correctly set.
Here’s your modified script with these considerations:
@echo off setlocal enabledelayedexpansion set MAX_CONCURRENT=3 set /a currentCount=0 set "summaryFile=log\summary.log" :: Initialize or clear the summary log echo Summary of ongoing work > "%summaryFile%" echo ======================= >> "%summaryFile%" echo. >> "%summaryFile%" :StartBatchLoop :: Count how many semaphore files are created set /a currentCount=0 for /f %%i in ('dir /b "log\semaphore\*.sem" 2^>nul ^| find /c /v ""') do set currentCount=%%i :: If we have reached the maximum, wait and check again if !currentCount! geq %MAX_CONCURRENT% ( timeout /t 1 >nul goto StartBatchLoop ) :: Read the office_ids from st.txt for /f "usebackq delims=" %%a in ("st.txt") do ( set "store_id=%%a" set "serv_id=PTH%%a" :: Create semaphore file for the current office_id echo. > "log\semaphore\process_%%a.semaphore" :: Ping the office_id (assumed to be an IP address or hostname) ping -n 1 !serv_id! -w 1000 >nul if errorlevel 1 ( echo %%a is offline, skipping... echo %%a is offline >> "%summaryFile%" del "log\semaphore\process_%%a.semaphore" >nul 2>&1 goto EndOfficeIdIteration ) else ( echo %%a is online, performing operations... echo %%a is online >> "%summaryFile%" :: Note the start time echo Processing %%a started at %time% >> "%summaryFile%" :: Run your batch file in the background start /b cmd /c "C:\path\to\your\batchfile.bat %%a" ) :: Wait for the batch file to finish :WaitForBatch timeout /t 1 >nul if exist "log\semaphore\process_%%a.semaphore" ( goto WaitForBatch ) :: Log the end time echo Processing %%a finished at %time% >> "%summaryFile%" :: Display the current summary log echo. echo Current Summary Log: type "%summaryFile%" echo. del "log\semaphore\process_%%a.semaphore" :EndOfficeIdIteration ) :: Go back to start the next batch file goto StartBatchLoopKey Modifications:
-
Enabled Delayed Expansion: At the start of the script, I used the command
setlocal enabledelayedexpansionto allow for delayed variable expansion, which is crucial when you're modifying and using variables within loops. -
Using
!currentCount!: Changed the usage ofcurrentCountto!currentCount!during comparison. -
General Cleanup: The script already seems to handle operations correctly regarding semaphore files and processing output.
Final Notes:
- Make sure to keep an eye on the paths defined (
log\,st.txt, and the batch file path). They should be valid and exist on your system. - Test the script to ensure it behaves as intended, especially with regards to concurrent executions and logging to your summary file.
- Adjust
timeout /tdelays to suit your processing needs, particularly if the operations in your background batch might take varying times.
-
- User
make checking folder log and clean
- Assistant
To make your batch script check for the existence of the
logfolder, create it if it doesn't exist, and optionally clean up the contents (like removing old semaphore files and the summary log), you can add a few additional commands at the beginning of your script. Here's how to structure the updated script:@echo off setlocal enabledelayedexpansion set MAX_CONCURRENT=3 set /a currentCount=0 set "logFolder=log" set "summaryFile=%logFolder%\summary.log" set "semaphoreFolder=%logFolder%\semaphore" :: Create log directory if it does not exist if not exist "%logFolder%" ( mkdir "%logFolder%" ) :: Create semaphore directory if it does not exist if not exist "%semaphoreFolder%" ( mkdir "%semaphoreFolder%" ) :: Optional: Clean up the log directory :: Uncomment the following lines to clean up :: echo Cleaning up old logs and semaphore files... :: del "%summaryFile%" >nul 2>&1 :: del "%semaphoreFolder%\*.sem" >nul 2>&1 :: Initialize or clear the summary log echo Summary of ongoing work > "%summaryFile%" echo ======================= >> "%summaryFile%" echo. >> "%summaryFile%" :StartBatchLoop :: Count how many semaphore files are created set /a currentCount=0 for /f %%i in ('dir /b "%semaphoreFolder%\*.sem" 2^>nul ^| find /c /v ""') do set currentCount=%%i :: If we have reached the maximum, wait and check again if !currentCount! geq %MAX_CONCURRENT% ( timeout /t 1 >nul goto StartBatchLoop ) :: Read the office_ids from st.txt for /f "usebackq delims=" %%a in ("st.txt") do ( set "store_id=%%a" set "serv_id=PTH%%a" :: Create semaphore file for the current office_id echo. > "%semaphoreFolder%\process_%%a.semaphore" :: Ping the office_id (assumed to be an IP address or hostname) ping -n 1 !serv_id! -w 1000 >nul if errorlevel 1 ( echo %%a is offline, skipping... echo %%a is offline >> "%summaryFile%" del "%semaphoreFolder%\process_%%a.semaphore" >nul 2>&1 goto EndOfficeIdIteration ) else ( echo %%a is online, performing operations... echo %%a is online >> "%summaryFile%" :: Note the start time echo Processing %%a started at %time% >> "%summaryFile%" :: Run your batch file in the background start /b cmd /c "C:\path\to\your\batchfile.bat %%a" ) :: Wait for the batch file to finish :WaitForBatch timeout /t 1 >nul if exist "%semaphoreFolder%\process_%%a.semaphore" ( goto WaitForBatch ) :: Log the end time echo Processing %%a finished at %time% >> "%summaryFile%" :: Display the current summary log echo. echo Current Summary Log: type "%summaryFile%" echo. del "%semaphoreFolder%\process_%%a.semaphore" :EndOfficeIdIteration ) :: Go back to start the next batch file goto StartBatchLoopKey Additions and Changes:
-
Create Directories:
- The script now checks if the
logdirectory andsemaphoresubdirectory exist. If they don't, it creates them usingmkdir.
- The script now checks if the
-
Optional Cleanup:
- I've added optional cleanup commands to remove any existing summary log file and semaphore files from the previous runs. This is commented out; you can uncomment those lines if you want the script to clean up upon each execution.
-
Using Variables for the Log and Semaphore Paths:
- Paths for the summary file and semaphore files use variables (
logFolderandsemaphoreFolder). This ensures that changes in the directory structure or naming only need to be done in one place.
- Paths for the summary file and semaphore files use variables (
Caution:
- The cleanup section is commented out to prevent accidental data loss. You should review this part carefully before enabling it.
- Be sure to test the script in a safe environment before deploying it in production, particularly if it includes file deletions.
-
- User
make simple batch file to check the program by
- input id
- change id to pth%id%
- ping -n 1 pth%id%
- Assistant
Creating a simple batch file that accomplishes the tasks you've specified is quite straightforward. Below is an example of such a batch file script. It prompts the user to input an ID, constructs a hostname by prefixing
PTH, and then pings the constructed hostname.Simple Batch File Script
@echo off setlocal :: Prompt user for input ID set /p id="Enter ID: " :: Construct the server name with 'PTH' prefix set "serverName=PTH%id%" :: Inform the user of the server being pinged echo Pinging %serverName%... :: Ping the server ping -n 1 %serverName% :: Check the error level of the ping command if errorlevel 1 ( echo %serverName% is offline. ) else ( echo %serverName% is online. ) :: End of script endlocal pauseExplanation of the Script:
- Prompt for Input: The script uses
set /pto prompt the user to enter an ID. - Construct the Server Name: The ID entered by the user is concatenated with the prefix
PTHto create aserverName. - Ping the Server: The script then pings the constructed
serverName(which isPTH<ID>). - Check the Ping Result: After attempting to ping, the script checks the
errorlevel. If it's1(meaning the ping failed), it will print that the server is offline; otherwise, it prints that the server is online. - Pause Before Exit: The script ends with a
pausecommand to keep the command window open until the user decides to close it.
How to Use:
- Copy the code above into a text file.
- Save the file with a
.batextension (e.g.,check_server.bat). - Double-click the batch file to run it. It will prompt you to enter an ID, construct the hostname, and ping it.
Make sure that the IDs you input correspond to valid hostnames or IP addresses on your network for the scripts to produce the expected results.
- Prompt for Input: The script uses
- User
make main concurrent to call this check_server.bat
- Assistant
To create a main batch script that runs multiple instances of
check_server.batconcurrently based on the input IDs, you can organize the folders into a structure where your main script reads from a file containing IDs, similar to how the previous example worked. This main script will callcheck_server.batin the background, allowing multiple pings to occur at the same time.Here's an example of how to structure this main script, assuming you have the
check_server.batfile in the same directory as your main script or appropriately referenced.Main Concurrent Batch Script
@echo off setlocal enabledelayedexpansion set MAX_CONCURRENT=3 set /a currentCount=0 set "summaryFile=log\summary.log" :: Create a log directory if it doesn't exist if not exist "log" ( mkdir "log" ) :: Initialize or clear the summary log echo Summary of ongoing pings > "%summaryFile%" echo ======================= >> "%summaryFile%" echo. >> "%summaryFile%" :StartBatchLoop :: Count how many pings are currently in process set /a currentCount=0 for /f %%i in ('tasklist /FI "WINDOWTITLE eq cmd.exe" ^| find /c /v ""') do set currentCount=%%i :: If we reached the max concurrent limit if !currentCount! geq %MAX_CONCURRENT% ( timeout /t 1 >nul goto StartBatchLoop ) :: Read the IDs from a file named ids.txt for /f "usebackq delims=" %%a in ("ids.txt") do ( set "id=%%a" :: Start the check_server.bat script in the background echo Starting ping for PTH!id! ... start "" cmd /c "check_server.bat !id! >> "%summaryFile%" 2>&1" :: Optional: Log the start of the ping echo PTH!id! started at %time% >> "%summaryFile%" ) :: Go back to check for more concurrent pings goto StartBatchLoop :: End of script endlocalExplanation of the Main Script:
-
Max Concurrent Pings: The script sets a maximum number of concurrent pings with
MAX_CONCURRENT, which is set to3in this example. -
Counting Current Pings: It uses
tasklistto count how many Command Prompt windows are currently running. This will help manage how many concurrentcheck_server.batscripts are executed. -
Check for IDs: It reads from a file named
ids.txt, where each line should contain one ID. -
Start
check_server.bat:- For each ID read from
ids.txt, it constructs the command to runcheck_server.batwith the ID. - It runs
check_server.batin the background withcmd /c, redirecting both output and errors to a summary log file for tracking purposes.
- For each ID read from
-
Logging: Each start of a ping is logged with a timestamp into
summary.log. -
Handling Concurrent Processes: If the number of concurrent pings reaches the defined limit, the script waits for a second before checking again.
How to Use:
- Save the provided batch code as your main script (e.g.,
main_ping.bat). - Ensure
check_server.batis saved in the same directory or adjust the path accordingly in thestartcommand. - Create a new file called
ids.txtin the same directory, containing one ID per line (e.g.,id1on one line,id2on the next, etc.). - When you run the
main_ping.batscript, it will read the IDs fromids.txt, launch pings concurrently, and log the results tolog\summary.log.
Note:
- Make sure that the IDs you use are valid for your network/application needs.
- Test the script first to ensure it meets your requirements, focusing on network constraints and behavior during high concurrency.
-
- User
for /f %%i in ('tasklist /FI "WINDOWTITLE eq cmd.exe" ^| find /c /v ""') do set currentCount=%%i
make create file and count file for job
- Assistant
To create a file that tracks jobs and potentially counts them for managing concurrent executions, you can modify your batch script to create a job file every time a
check_server.batprocess is started and then keep track of how many job files exist for limiting the number of concurrent pings.Below is an updated version of the main script that:
- Creates a job file whenever
check_server.batis started. - Uses the presence of these job files to count the current active jobs.
Main Concurrent Batch Script with Job Tracking
@echo off setlocal enabledelayedexpansion set MAX_CONCURRENT=3 set "jobFolder=log\jobs" set /a currentCount=0 set "summaryFile=log\summary.log" :: Create necessary directories if not exist "log" ( mkdir "log" ) if not exist "%jobFolder%" ( mkdir "%jobFolder%" ) :: Initialize or clear the summary log echo Summary of ongoing pings > "%summaryFile%" echo ======================= >> "%summaryFile%" echo. >> "%summaryFile%" :StartBatchLoop :: Count current job files set /a currentCount=0 for /f %%i in ('dir /b "%jobFolder%\*.job" 2^>nul ^| find /c /v ""') do set currentCount=%%i :: If we reached the max concurrent limit, wait if !currentCount! geq %MAX_CONCURRENT% ( timeout /t 1 >nul goto StartBatchLoop ) :: Read the IDs from a file named ids.txt for /f "usebackq delims=" %%a in ("ids.txt") do ( set "id=%%a" :: Create a job file for tracking (to manage concurrent jobs) echo Job for PTH!id! > "%jobFolder%\job_%%a.job" :: Start the check_server.bat script in the background echo Starting ping for PTH!id! ... start "" cmd /c "check_server.bat !id! >> "%summaryFile%" 2>&1" :: Optional: Log the start of the ping echo PTH!id! started at %time% >> "%summaryFile%" ) :: Go back to check for more concurrent pings goto StartBatchLoop :: End of script endlocalKey Additions and Changes:
-
Job Folder Creation:
- A new directory named
jobsinside thelogdirectory is created if it does not exist. This directory will store job files.
- A new directory named
-
Job File Creation:
- Each time a ping job starts, a corresponding job file (e.g.,
job_id.job) is created in thelog\jobsdirectory to indicate that a job is active.
- Each time a ping job starts, a corresponding job file (e.g.,
-
Counting Running Jobs:
- The script counts how many job files currently exist in the
jobsfolder, allowing you to manage how many concurrent jobs are being executed based on the number of.jobfiles.
- The script counts how many job files currently exist in the
-
Using Job Files for Tracking:
- As job files remain until you explicitly delete them, you can monitor the state (e.g., how many jobs are running).
Cleanup
You'll want to implement cleanup for job files once the corresponding
check_server.batcompletes. You can add this cleanup incheck_server.batitself by removing the job file at the end of the script. Here’s how to modifycheck_server.batto handle that:Check Server Script Modification
@echo off setlocal :: Get the ID passed from the main script set "id=%1" :: Construct the server name with 'PTH' prefix set "serverName=PTH%id%" :: Inform the user of the server being pinged echo Pinging %serverName%... :: Ping the server ping -n 1 %serverName% :: Check the error level of the ping command if errorlevel 1 ( echo %serverName% is offline. ) else ( echo %serverName% is online. ) :: Cleanup: Remove the job file for this ID del "log\jobs\job_%id%.job" >nul 2>&1 :: End of script endlocalFinal Notes:
- Make sure all paths are correct according to your directory structure.
- Ensure that
ids.txtcontains valid IDs for your use case. - Monitor the log files and job files for expected behaviors, especially under high usage loads.
- Creates a job file whenever
- User
make read file by first part because st.txt is 12345 name, 12346 name2 and make limit loop for job prevent infinity loop
- Assistant
To enhance your script so that it reads from
st.txtin a structured way (extracting the first part—like an ID), and to impose a limit on the number of jobs processed to prevent infinite loops, we can make several modifications.Here's how we will achieve that:
-
Extract First Part of Each Line: We will use a delimiter to split each line in
st.txtand get only the first part (the ID). -
Limit the Number of Jobs: We will implement a simple counter to keep track of how many jobs have been processed, allowing you to break out of the loop after a certain number of jobs have been processed.
Updated Main Concurrent Batch Script
Here's the modified version of your main script:
@echo off setlocal enabledelayedexpansion set MAX_CONCURRENT=3 set "jobFolder=log\jobs" set "summaryFile=log\summary.log" set /a jobLimit=10 :: Set a limit for the number of jobs to process set /a totalJobsProcessed=0 :: Tracker for total jobs processed :: Create necessary directories if not exist "log" ( mkdir "log" ) if not exist "%jobFolder%" ( mkdir "%jobFolder%" ) :: Initialize or clear the summary log echo Summary of ongoing pings > "%summaryFile%" echo ======================= >> "%summaryFile%" echo. >> "%summaryFile%" :StartBatchLoop :: Count current job files set /a currentCount=0 for /f %%i in ('dir /b "%jobFolder%\*.job" 2^>nul ^| find /c /v ""') do set currentCount=%%i :: If we reached the max concurrent limit, wait if !currentCount! geq %MAX_CONCURRENT% ( timeout /t 1 >nul goto StartBatchLoop ) :: Read the IDs from a file named st.txt for /f "usebackq tokens=1 delims= " %%a in ("st.txt") do ( set "id=%%a" :: Check if we've hit the job limit if !totalJobsProcessed! geq !jobLimit! ( echo Processed the maximum limit of jobs: !jobLimit!. goto Done ) :: Create a job file for tracking (to manage concurrent jobs) echo Job for PTH!id! > "%jobFolder%\job_%%a.job" :: Start the check_server.bat script in the background echo Starting ping for PTH!id! ... start "" cmd /c "check_server.bat !id! >> "%summaryFile%" 2>&1" :: Optional: Log the start of the ping echo PTH!id! started at %time% >> "%summaryFile%" :: Increment the counter for processed jobs set /a totalJobsProcessed+=1 :: Optional small delay to prevent rapid-fire starts timeout /t 1 >nul ) :: Go back to check for more concurrent pings goto StartBatchLoop :Done :: End of script endlocalKey Changes and Features:
-
Reading from
st.txt:- The
forloopfor /f "usebackq tokens=1 delims= " %%a in ("st.txt")reads each line; thetokens=1retrieves only the first part (before the first space) of each entry inst.txt.
- The
-
Job Limit:
- A variable
jobLimitis defined to set the maximum number of jobs to process (here it is set to 10). - A counter
totalJobsProcessedis maintained to keep track of how many jobs have been started. If this counter exceeds thejobLimit, the script will break out of the loop and finish.
- A variable
-
Prevention of Rapid Starts:
- Added a small delay (
timeout /t 1) after starting each job to avoid starting jobs too quickly, which can lead to rapid fire and overwhelm system resources.
- Added a small delay (
-
Exit Condition:
- After checking all lines in
st.txt, it goes back to waiting for job limits and concurrent processing.
- After checking all lines in
Final Notes:
- Make sure to test this script thoroughly in your environment to ensure it behaves as expected, especially seeing how it handles the limit and concurrent execution.
- Modify
jobLimitbased on how many concurrent jobs you want to manage at a given time. - Ensure that your
st.txtis formatted correctly, with IDs and names separated appropriately for the script to function correctly.
-
- User
@echo off setlocal enabledelayedexpansion
set MAX_CONCURRENT=3 set "jobFolder=log\jobs" set "summaryFile=log\summary.log" set /a jobLimit=3 :: Set a limit for the number of jobs to process set /a totalJobsProcessed=0 :: Tracker for total jobs processed
:: Create necessary directories if not exist "log" ( mkdir "log" )
if not exist "%jobFolder%" ( mkdir "%jobFolder%" )
:: Initialize or clear the summary log echo Summary of ongoing pings > "%summaryFile%" echo ======================= >> "%summaryFile%" echo. >> "%summaryFile%"
:StartBatchLoop :: Count current job files set /a currentCount=0 for /f %%i in ('dir /b "%jobFolder%*.job" 2^>nul ^| find /c /v ""') do set currentCount=%%i
:: If we reached the max concurrent limit, wait if !currentCount! geq %MAX_CONCURRENT% ( timeout /t 1 >nul goto StartBatchLoop )
:: Read the IDs from a file named st.txt for /f "usebackq tokens=1 delims=| " %%a in ("st.txt") do ( set "st_id=%%a"
:: Check if we've hit the job limit if !totalJobsProcessed! geq !jobLimit! ( echo Processed the maximum limit of jobs: !jobLimit!. goto Done ) :: Create a job file for tracking (to manage concurrent jobs) echo Job for PTH!st_id! > "%jobFolder%\job_%%a.job" :: Start the check_server.bat script in the background echo Starting ping for PTH!st_id! ... start /b "" cmd /c "test.bat !st_id! >> "%summaryFile%" 2>&1" :: Optional: Log the start of the ping echo PTH!st_id! started at %time% >> "%summaryFile%" :: Increment the counter for processed jobs set /a totalJobsProcessed+=1 :: Optional small delay to prevent rapid-fire starts timeout /t 1 >nul)
:: Go back to check for more concurrent pings goto StartBatchLoop
:Done :: End of script endlocal
อะไรคือความแตกต่างของ maxconcurrent และ job limit
- Assistant
The concepts of MAX_CONCURRENT and jobLimit in your batch script serve different purposes when controlling the flow of concurrent processes. Here's a breakdown of the differences:
MAX_CONCURRENT:
- Purpose: This variable limits the number of simultaneous processes (jobs) running at any given time.
- Usage in Script: It is checked in the loop where the script counts the current jobs based on the presence of job files in the
log\jobsdirectory. - Behavior: If the number of currently active jobs (tracked by the presence of job files) reaches or exceeds
MAX_CONCURRENT, the script will pause and wait (timeout /t 1) before checking again. This helps prevent overloading the system with too many concurrent processes.
jobLimit:
- Purpose: This variable limits the total number of jobs that can be started during the entire execution of the script.
- Usage in Script: It is used to determine how many jobs have already been processed (
totalJobsProcessed), and checks this againstjobLimitin the loop that reads IDs fromst.txt. - Behavior: Once the number of successfully initiated jobs hits
jobLimit, the script will stop processing any further jobs, regardless of how many concurrent jobs might still be running. This prevents scenarios where the script would continuously read fromst.txtand try to start new jobs indefinitely.
In Summary
- MAX_CONCURRENT focuses on managing how many jobs are active at the same time, hence controlling concurrency to avoid overwhelming resources.
- jobLimit tracks the total number of jobs submitted through the entire session of the script, allowing you to set a cap on how much work the script can initiate.
Example Scenario
For example, if
MAX_CONCURRENTis set to 3 andjobLimitis set to 10:- The script can run up to 3 jobs concurrently, processing them as they complete.
- However, it will not start more than 10 jobs total during its execution, even if the active jobs drop below 3 during its runtime.
This way, you can ensure that the system is not overloaded with too many jobs at once while also maintaining a defined maximum for overall job processing.
- User
remove joblimit
- Assistant
If you want to remove the
jobLimitfunctionality from your batch script while maintaining the concurrent job control withMAX_CONCURRENT, you can simplify the script accordingly. Below is the updated version of your script without thejobLimitcounter:Updated Main Concurrent Batch Script Without Job Limit
@echo off setlocal enabledelayedexpansion set MAX_CONCURRENT=3 set "jobFolder=log\jobs" set "summaryFile=log\summary.log" :: Create necessary directories if not exist "log" ( mkdir "log" ) if not exist "%jobFolder%" ( mkdir "%jobFolder%" ) :: Initialize or clear the summary log echo Summary of ongoing pings > "%summaryFile%" echo ======================= >> "%summaryFile%" echo. >> "%summaryFile%" :StartBatchLoop :: Count current job files set /a currentCount=0 for /f %%i in ('dir /b "%jobFolder%\*.job" 2^>nul ^| find /c /v ""') do set currentCount=%%i :: If we reached the max concurrent limit, wait if !currentCount! geq %MAX_CONCURRENT% ( timeout /t 1 >nul goto StartBatchLoop ) :: Read the IDs from a file named st.txt for /f "usebackq tokens=1 delims=| " %%a in ("st.txt") do ( set "st_id=%%a" :: Create a job file for tracking (to manage concurrent jobs) echo Job for PTH!st_id! > "%jobFolder%\job_%%a.job" :: Start the check_server.bat script in the background echo Starting ping for PTH!st_id! ... start /b "" cmd /c "test.bat !st_id! >> "%summaryFile%" 2>&1" :: Optional: Log the start of the ping echo PTH!st_id! started at %time% >> "%summaryFile%" :: Optional small delay to prevent rapid-fire starts timeout /t 1 >nul ) :: Go back to check for more concurrent pings goto StartBatchLoop :: End of script endlocalKey Changes:
- Removed jobLimit: The
jobLimitand its associated tracking variables and checks have been completely removed from the script. - Simplified Logic: The script now only focuses on managing the maximum concurrent jobs allowed by
MAX_CONCURRENT. - Job Creation: The script still creates job files for tracking purposes, but it will run indefinitely as long as there are IDs to process from
st.txt.
Behavior:
- The script will continuously check how many concurrent jobs are running (based on the presence of job files) and will wait if the limit (defined by
MAX_CONCURRENT) is reached. - As long as there are IDs in
st.txt, it will keep processing them, starting a new job (or ping) in the background whenever it can do so without exceeding the maximum allowed concurrency.
Important Considerations:
- Ensure that your
st.txthas valid IDs, and consider how you want to manage the scenario where all IDs have been processed or if there are ongoing active jobs. You might want to introduce a way to handle program termination or to avoid running into infinite loops with an emptyst.txt. - If you want to stop the script, you'll need to handle that logic, as it will continue to loop and check for jobs.
- Removed jobLimit: The
- User
make type summaryfile to report user
- Assistant
To include functionality in your batch script that displays the contents of the summary file (
summary.txt) to the user, you can use thetypecommand after the jobs have been processed.Complete Batch Script With Summary Report
Here’s how you can modify your main batch script to type the contents of the summary file at the end or whenever required:
@echo off setlocal enabledelayedexpansion set MAX_CONCURRENT=3 set "jobFolder=log\jobs" set "summaryFile=log\summary.log" :: Create necessary directories if not exist "log" ( mkdir "log" ) if not exist "%jobFolder%" ( mkdir "%jobFolder%" ) :: Initialize or clear the summary log echo Summary of ongoing pings > "%summaryFile%" echo ======================= >> "%summaryFile%" echo. >> "%summaryFile%" :StartBatchLoop :: Count current job files set /a currentCount=0 for /f %%i in ('dir /b "%jobFolder%\*.job" 2^>nul ^| find /c /v ""') do set currentCount=%%i :: If we reached the max concurrent limit, wait if !currentCount! geq %MAX_CONCURRENT% ( timeout /t 1 >nul goto StartBatchLoop ) :: Read the IDs from a file named st.txt for /f "usebackq tokens=1 delims=| " %%a in ("st.txt") do ( set "st_id=%%a" :: Create a job file for tracking (to manage concurrent jobs) echo Job for PTH!st_id! > "%jobFolder%\job_%%a.job" :: Start the check_server.bat script in the background echo Starting ping for PTH!st_id! ... start /b "" cmd /c "test.bat !st_id! >> "%summaryFile%" 2>&1" :: Optional: Log the start of the ping echo PTH!st_id! started at %time% >> "%summaryFile%" :: Optional small delay to prevent rapid-fire starts timeout /t 1 >nul ) :: Display the summary log after all jobs have been started echo. echo Summary of ongoing pings: type "%summaryFile%" echo. :: Go back to check for more concurrent pings goto StartBatchLoop :: End of script endlocalKey Modifications:
-
Type Command:
- The
type "%summaryFile%"command is called right after all job starts to display the contents ofsummary.login the command prompt. - It provides the user with a view of the summary of ongoing pings, so they can see which jobs have started and their statuses.
- The
-
User-Friendly Output:
- A clear message (
Summary of ongoing pings:) helps define the output for the user, ensuring clarity on what is being displayed.
- A clear message (
Behavior:
- When the script is executed, it will process IDs from
st.txt, launchingcheck_server.batin the background until the concurrency limit is reached. - After starting all jobs (or if jobs are continuously being started), the summary of pings will be printed to the console for the user to review.
- The output will show the status of each ping initiated by
check_server.bat.
Additional Considerations:
- Pause: If you want the user to have time to read the summary before the script continues or the command window closes, you may consider adding a
pausecommand after typing the summary to wait for user input before proceeding. - Error Handling: Consider adding error handling to ensure that if
st.txtis empty or missing, the script behaves gracefully.
-