Sleep: Difference between revisions

From LemonWiki共筆
Jump to navigation Jump to search
No edit summary
Tags: Mobile edit Mobile web edit
Line 30: Line 30:
# Key-in {{kbd | key=<nowiki>where sleep</nowiki>}} or {{kbd | key=<nowiki>dir C:\cygwin64\bin\sleep.exe</nowiki>}} if the installation path of CygWin is {{kbd | key=<nowiki>C:\cygwin64\</nowiki>}}.
# Key-in {{kbd | key=<nowiki>where sleep</nowiki>}} or {{kbd | key=<nowiki>dir C:\cygwin64\bin\sleep.exe</nowiki>}} if the installation path of CygWin is {{kbd | key=<nowiki>C:\cygwin64\</nowiki>}}.
<pre>
<pre>
C:\Users\user>dir C:\cygwin64\bin\sleep.exe
# successful condition
# successful condition
C:\Users\user>dir C:\cygwin64\bin\sleep.exe
C:\cygwin64\bin\sleep.exe
C:\cygwin64\bin\sleep.exe



Revision as of 19:38, 3 November 2018

Sleep random seconds in programming

MS-DOS

Approach 1: %RANDOM% + ping local

batch file - .bat random timeout - Stack Overflow

  • %RANDOM% returns an integer between 0 and 32767.
  • 60 is the range of values you want: 0 to 60.
  • 32768 is the range of values returned by %RANDOM% (0 to 32767).
  • 5 is the minimum value you want. The original range of values you want '0 to 60' became '5 ~ 65'.
  • ping local address[1]

BAT file:

REM print current date & time
ECHO %date% %time%

REM sleep 5 ~ 65 seconds
SET /a timeout=%RANDOM% * 60 / 32768 + 5
ping 127.0.0.1 -n %timeout% > nul

REM print current date & time
ECHO %date% %time%

Approach 2: sleep package of CygWin

Requirement: Install Cygwin on Win Os windows.png & install sleep package

Verify the installation of sleep package[2][3]

  1. Key-in cmd to open command prompt (How to Open Command Prompt (Windows 10, 8, 7, Vista, XP))
  2. Key-in where sleep or dir C:\cygwin64\bin\sleep.exe if the installation path of CygWin is C:\cygwin64\.
C:\Users\user>dir C:\cygwin64\bin\sleep.exe

# successful condition
C:\cygwin64\bin\sleep.exe

# failed condition
File Not Found

BAT file:

REM print current date & time
ECHO %date% %time%

REM sleep 5 ~ 65 seconds
SET /a timeout=%RANDOM% * 60 / 32768 + 5
C:\cygwin64\bin\sleep.exe %timeout%

REM print current date & time
ECHO %date% %time%

Approach 3: TIMEOUT

Alternative command: Icon_exclaim.gif The following command ECHO %date% %time% will not be executed after TIMEOUT %timeout% was executed.

BAT file:

SET /a timeout=%RANDOM% * 60 / 32768 + 5
TIMEOUT %timeout%

ECHO %date% %time%

BASH

Tested on Linux Os linux.png & Mac icon_os_mac.png

# print current date & time
echo $(date '+%Y-%m-%d %H:%M:%S')

# sleep 5 ~ 65 seconds
timeout=$(($RANDOM * 60 / 32768 + 5))
sleep $timeout

# print current date & time
echo $(date '+%Y-%m-%d %H:%M:%S')

PHP

References

Related