Sleep: Difference between revisions

79,866 bytes added ,  3 months ago
m
→‎{{header|Wren}}: Changed to Wren S/H
No edit summary
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(200 intermediate revisions by more than 100 users not shown)
Line 1:
{{task|Basic language learning}}
 
;Task:
Write a program that does the following in this order:
* Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
* [[Hello world/Text|Print]] "Sleeping..."
* Sleep the main [[thread]] for the given amount of time.
* Print "Awake!"
* End.
<br>
 
;Related task:
* &nbsp; [[Nautical bell]]
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">V seconds = Float(input())
print(‘Sleeping...’)
sleep(seconds)
print(‘Awake!’)</syntaxhighlight>
 
=={{header|360 Assembly}}==
REENTRANT means the program can be called from several callers simultaneously. The program obtains storage (memory) at each invocation.
Sleep (logically swapped out task) is established through STIMER macro (SVC 47)
<syntaxhighlight lang="360 assembly">
START
PRINT DATA,GEN
YREGS , REGISTER EQUATES (e.g. 0 = R0)
SLEEP CSECT
SLEEP AMODE 31 addressing mode 31 bit
SLEEP RMODE ANY loader determines 31 or 24
***********************************************************************
* REENTRANT. Logically swap out a task for a number of seconds
* specified in PARM. Minimum 0, maximum 60 seconds
*
* MVS rexx (the original rexx) does not have a sleep function. This
* program can be called from rexx, assuming this program is in
* LINKLIST, as follows:
*
* /* rexx */
* wait_time = '6' /* number of seconds to sleep */
* say 'Sleeping...'
* address LINKMVS "SLEEP wait_time" /* invoke SLEEP */
* say 'Awake!
***********************************************************************
PROLOG BAKR R14,0 satck caller's registers
LR R4,R1 save parm pointer
LR R12,R15 entry point addr to R12
USING SLEEP,R12 tell assembler about that
B AROUND avoid abend S0C1
DC C'SLEEP ' CSECT NAME
DC C'C=2014.05.10 ' CHANGE DATE
DC C'A=&SYSDATE ' ASSEMBLY DATE
DC C'T=&SYSTIME ' CHANGE TIME
DC C'MarcvdM. ' PROGRAMMER NAME
AROUND L R10,0(0,R4) load parm address in R10
XR R15,R15 clear R15
LH R15,0(0,R10) load parm length in R15
LR R6,R15 save length in R6
LTR R15,R15 parm length 0?
BZ NOPARM yes, exit before getmain
C R6,F2 parmlength > 2 ?
BH NOPARM yes, exit before getmain
STORAGE OBTAIN,LENGTH=WALEN,LOC=ANY get some storage
LR R9,R1 address of storage in R9
USING WAREAX,R9 base for data section (DSECT)
MVC EYECAT,=C'**MARC**' make storage easy to find in dump
MVC SECONDS,C00 set field to F0F0
C R6,F1 parmlength = 1?
BNE COPYSECS no, copy both bytes
MVC SECONDS+1(1),2(R10) yes, just copy one byte.
B TRTEST
COPYSECS MVC SECONDS,2(R10)
* test supplied parameter for valid integer values
TRTEST TRT SECONDS(1),VALINT6 first parm byte no higher as 6?
BNZ NOPARM_REL higher, release storage and return
TRT SECONDS+1(1),VALINT9 second byte valid?
BNZ NOPARM_REL no, release storage and return
CLC SECONDS(1),=C'6' first parm byte < 6?
BNE DOWAIT yes, do wait
CLC SECONDS+1(1),=C'0' first eq. 6, second > 0?
BNE NOPARM_REL yes, release storage and return
DOWAIT DS 0H
MVC WAWTO(DWTOL),DWTO copy WTO list form to obtained st.
MVC WAWTO+18(2),SECONDS copy in nr. of seconds
WTO MF=(E,WAWTO) issue WTO, execute form
MVC HOURS,C00 zero out hours
MVC MINUTS,C00 and minutes
MVC REST,C00 and milliseconds
STIMER WAIT,DINTVL=TIMEVAL SVC 47: logical swap out (sleep)
B EXIT done
NOPARM_REL DS 0H
STORAGE RELEASE,ADDR=(R9),LENGTH=WALEN free obtained storage
LA R15,4 set return code 4
B RETURN return to caller
EXIT DS 0H
STORAGE RELEASE,ADDR=(R9),LENGTH=WALEN free obtained storage
WTO ' Awake!',ROUTCDE=11 fixed wake-up string
NOPARM EQU *
RETURN PR , return to caller
*
* --------------------------------------------------------------------
* CONSTANTS
* --------------------------------------------------------------------
DWTO WTO ' Sleeping... (XX seconds)',ROUTCDE=11,MF=L
DWTOL EQU *-DWTO length of WTO list form
F1 DC F'1'
F2 DC F'2'
C00 DC C'00'
VALINT6 DC 256XL1'01'
ORG *-16
VALOK6 DC 7XL1'00' F0-F6: OFFSETS 240-246
VALINT9 DC 256XL1'01'
ORG *-16
VALOK9 DC 10XL1'00' F0-F9: OFFSETS 240-249
DS 0D
LTORG , FORCE DISPLACEMENT LITERALS
* --------------------------------------------------------------------
* DSECT (data section)
* --------------------------------------------------------------------
WAREAX DSECT ,
WAWTO DS CL(DWTOL) reentrant WTO area
EYECAT DS CL8
TIMEVAL DS 0CL8
HOURS DS CL2 will be zeroed
MINUTS DS CL2 will be zeroed
SECONDS DS CL2 from parm
REST DS CL2 will be zeroed
WALEN EQU *-WAREAX length of DSECT
* --------------------------------------------------------------------
END SLEEP
</syntaxhighlight>
'''output''' invoked with PARM='6' (+ sign indicates "problem state" (non system key) execution
<pre style="overflow:scroll">
+ Sleeping... (06 seconds)
+ Awake!
</pre>
 
=={{header|8051 Assembly}}==
Input and output is dependent on hardware. The time units are machine cycles, which depends both on the oscillator frequency and the oscillator periods to machine cycle conversion factor. This code puts the processor into 'idle' mode, where code execution is stopped and resumed via an interrupt.
<syntaxhighlight lang="asm">ORG RESET
jmp main
ORG TIMER0
; timer interrupt only used to wake the processor
clr tr0
reti
 
main:
setb ea ; enable interrupts
setb et0 ; enable timer0 interrupt
mov tl0, #0 ; start timer counter at zero
mov th0, #0 ; these two values dictate the length of sleep
 
mov a, pcon ; copy power control register
setb a.0 ; set idl bit
setb tr0 ; start timer
; sleeping...
mov pcon, a ; move a back into pcon (processor sleeps after this instruction finishes)
 
; when the timer overflows and the timer interrupt returns, execution will resume at this spot
 
; Awake!
jmp $</syntaxhighlight>
 
=={{header|8th}}==
<syntaxhighlight lang="forth">
f:stdin f:getline
"Sleeping..." . cr
eval sleep
"Awake!" . cr bye
</syntaxhighlight>
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program sleep64.s */
 
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeConstantesARM64.inc"
 
.equ SLEEP, 0x65 // Linux syscall
.equ BUFFERSIZE, 100
/*******************************************/
/* Initialized data */
/*******************************************/
.data
szMessQuest: .asciz "Enter the time to sleep in seconds : "
szMessError: .asciz "Error occured.\n"
szMessSleep: .asciz "Sleeping Zzzzzzz.\n"
szMessAwake: .asciz "Awake!!!\n"
szCarriageReturn: .asciz "\n"
/*******************************************/
/* UnInitialized data */
/*******************************************/
.bss
.align 4
ZonesAttente:
qSecondes: .skip 8
qMicroSecondes: .skip 8
ZonesTemps: .skip 16
sBuffer: .skip BUFFERSIZE
/*******************************************/
/* code section */
/*******************************************/
.text
.global main
main:
ldr x0,qAdrszMessQuest // display invite message
bl affichageMess
mov x0,STDIN // input standard linux
ldr x1,qAdrsBuffer
mov x2,BUFFERSIZE
mov x8,READ // read input string
svc 0
cmp x0,0 // read error ?
ble 99f
//
ldr x0,qAdrsBuffer // buffer address
bl conversionAtoD // conversion string in number in x0
ldr x1,qAdrqSecondes
str x0,[x1] // store second number in area
ldr x0,qAdrszMessSleep // display sleeping message
bl affichageMess
ldr x0,qAdrZonesAttente // delay area
ldr x1,qAdrZonesTemps //
mov x8,#SLEEP // call system SLEEP
svc 0
cmp x0,#0 // error sleep ?
blt 99f
ldr x0,qAdrszMessAwake // display awake message
bl affichageMess
mov x0, #0 // return code
b 100f
99: // display error message
ldr x0,qAdrszMessError
bl affichageMess
mov x0, 1 // return code
100: // standard end of the program
mov x8,EXIT // request to exit program
svc 0 // perform system call
qAdrszMessQuest: .quad szMessQuest
qAdrszMessError: .quad szMessError
qAdrszMessSleep: .quad szMessSleep
qAdrszMessAwake: .quad szMessAwake
qAdrqSecondes: .quad qSecondes
qAdrZonesAttente: .quad ZonesAttente
qAdrZonesTemps: .quad ZonesTemps
qAdrsBuffer: .quad sBuffer
qAdrszCarriageReturn: .quad szCarriageReturn
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
<pre>
Enter the time to sleep in seconds : 5
Sleeping Zzzzzzz.
Awake!!!
 
</pre>
=={{header|Action!}}==
<syntaxhighlight lang="action!">BYTE RTCLOK1=$13
BYTE RTCLOK2=$14
BYTE PALNTSC=$D014
 
PROC Wait(CARD frames)
BYTE lsb=frames,msb=frames+1
 
;wait lsb of frames
lsb==+RTCLOK2
WHILE lsb#RTCLOK2 DO OD
;wait msb of 256*frames
WHILE msb>0
DO
WHILE lsb=RTCLOK2 DO OD
WHILE lsb#RTCLOK2 DO OD
msb==-1
OD
RETURN
 
CARD FUNC GetFrame()
CARD res
BYTE lsb=res,msb=res+1
 
lsb=RTCLOK2
msb=RTCLOK1
RETURN (res)
 
CARD FUNC MsToFrames(CARD ms)
CARD res
 
IF PALNTSC=15 THEN
res=ms/60
ELSE
res=ms/50
FI
RETURN (res)
 
CARD FUNC FramesToMs(CARD frames)
CARD res
 
IF PALNTSC=15 THEN
res=frames*60
ELSE
res=frames*50
FI
RETURN (res)
 
PROC Main()
CARD ARRAY data=[1 5 10 50 100 500]
CARD beg,end,diff,diffMs,delay,delayMs
BYTE i
 
FOR i=0 TO 5
DO
delay=data(i)
delayMs=FramesToMs(delay)
PrintF("Wait %U frames / %U ms...%E",delay,delayMs)
 
beg=GetFrame()
Wait(delay)
end=GetFrame()
diff=end-beg
diffMs=FramesToMs(diff)
 
PrintF("Frame number at begin %U%E",beg)
PrintF("Frame number at end %U%E",end)
PrintF("Waited %U-%U=%U frames / %U ms%E%E",end,beg,diff,diffMs)
OD
RETURN</syntaxhighlight>
{{out}}
The following result has been obtained from PAL version of Atari 8-bit computer.
 
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Sleep.png Screenshot from Atari 8-bit computer]
<pre>
Wait 1 frames / 50 ms...
Frame number at begin 411
Frame number at end 412
Waited 412-411=1 frames / 50 ms
 
Wait 5 frames / 250 ms...
Frame number at begin 423
Frame number at end 428
Waited 428-423=5 frames / 250 ms
 
Wait 10 frames / 500 ms...
Frame number at begin 439
Frame number at end 449
Waited 449-439=10 frames / 500 ms
 
Wait 50 frames / 2500 ms...
Frame number at begin 460
Frame number at end 510
Waited 510-460=50 frames / 2500 ms
 
Wait 100 frames / 5000 ms...
Frame number at begin 521
Frame number at end 621
Waited 621-521=100 frames / 5000 ms
 
Wait 500 frames / 25000 ms...
Frame number at begin 635
Frame number at end 1135
Waited 1135-635=500 frames / 25000 ms
</pre>
 
=={{header|Ada}}==
Line 11 ⟶ 381:
The Ada delay statement takes an argument of type Duration, which is a real number counting the number of seconds to delay. Thus, 2.0 will delay 2.0 seconds, while 0.001 will delay 0.001 seconds.
 
<langsyntaxhighlight lang="ada">with Ada.Text_Io; use Ada.Text_Io;
with Ada.Float_Text_Io; use Ada.Float_Text_Io;
Line 21 ⟶ 391:
delay Duration(In_Val);
Put_Line("Awake!");
end Sleep;</langsyntaxhighlight>
 
=={{header|Aime}}==
<syntaxhighlight lang="aime">o_text("Sleeping...\n");
 
# Sleep X seconds
sleep(atoi(argv(1)));
 
# Sleep X microseconds
#usleep(atoi(argv(1)));
 
o_text("Awake!\n");</syntaxhighlight>
 
=={{header|ALGOL 68}}==
 
{{works with|ALGOL 68G|Any for Microsoft Windows - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-2.8/algol68g-2.8.win32.zip/download 2.8.win32]}}
Only works for Microsoft Windows because it uses Windows-specific ping syntax.
<syntaxhighlight lang="algol68"># using ping to sleep #
INT milliseconds = read int; # ping uses milliseconds #
print ("Sleeping...");
VOID (system ("ping 0.0.0.1 -n 1 -w " + whole (milliseconds, 0) + " >NUL"));
# 0.0.0.1 is an invalid IP address and cannot be used, so this will never conflict with a real IP address #
# ping -n gives number of tries, -w timeout, and >NUL deletes output so the user does not see it #
print (new line);
print ("Awake!")</syntaxhighlight>
 
=={{header|AntLang}}==
<syntaxhighlight lang="antlang">milliseconds: eval[input["How long should I sleep? "]] / eval = evil, but this is just a simple demo
echo["Sleeping..."]
sleep[milliseconds]
echo["Awake!"]</syntaxhighlight>
 
=={{header|Applesoft BASIC}}==
The cycles and times calculated should only be taken as a minimum delay.
<syntaxhighlight lang="applesoftbasic"> 10 POKE 768,169: POKE 770,76
20 POKE 771,168: POKE 772,252
30 INPUT "ENTER WAIT VALUE (1-256) : ";A
40 IF A < 1 OR A > 256 THEN 30
50 POKE 769,(A < 256) * A
60 LET C = (26 + 27 * A + 5 * A ^ 2) / 2
70 PRINT "WAIT FOR "C" CYCLES OR "
80 PRINT C * 14 / 14.318181" MICROSECONDS"
90 PRINT "SLEEPING": CALL 768: PRINT "AWAKE"</syntaxhighlight>
Output:<pre>ENTER WAIT VALUE (1-256) : 256
WAIT FOR 167309 CYCLES OR
163591.032 MICROSECONDS
SLEEPING
AWAKE
</pre>
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
 
/* ARM assembly Raspberry PI */
/* program sleepAsm.s */
 
/* Constantes */
.equ STDIN, 0 @ Linux input console
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ READ, 3 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
.equ SLEEP, 0xa2 @ Linux syscall
 
 
.equ BUFFERSIZE, 100
/* Initialized data */
.data
szMessQuest: .asciz "Enter the time to sleep in seconds : "
szMessError: .asciz "Error occured.\n"
szMessSleep: .asciz "Sleeping Zzzzzzz.\n"
szMessAwake: .asciz "Awake!!!\n"
 
szCarriageReturn: .asciz "\n"
 
/* UnInitialized data */
.bss
.align 4
ZonesAttente:
iSecondes: .skip 4
iMicroSecondes: .skip 4
ZonesTemps: .skip 8
sBuffer: .skip BUFFERSIZE
 
/* code section */
.text
.global main
main:
ldr r0,iAdrszMessQuest @ display invite message
bl affichageMess
mov r0,#STDIN @ input standard linux
ldr r1,iAdrsBuffer
mov r2,#BUFFERSIZE
mov r7,#READ @ read input string
svc 0
cmp r0,#0 @ read error ?
ble 99f
@
ldr r0,iAdrsBuffer @ buffer address
bl conversionAtoD @ conversion string in number in r0
 
ldr r1,iAdriSecondes
str r0,[r1] @ store second number in area
ldr r0,iAdrszMessSleep @ display sleeping message
bl affichageMess
ldr r0,iAdrZonesAttente @ delay area
ldr r1,iAdrZonesTemps @
mov r7,#SLEEP @ call system SLEEP
svc 0
cmp r0,#0 @ error sleep ?
blt 99f
ldr r0,iAdrszMessAwake @ display awake message
bl affichageMess
mov r0, #0 @ return code
b 100f
99: @ display error message
ldr r0,iAdrszMessError
bl affichageMess
mov r0, #1 @ return code
 
100: @ standard end of the program
mov r7, #EXIT @ request to exit program
svc 0 @ perform system call
iAdrszMessQuest: .int szMessQuest
iAdrszMessError: .int szMessError
iAdrszMessSleep: .int szMessSleep
iAdrszMessAwake: .int szMessAwake
iAdriSecondes: .int iSecondes
iAdrZonesAttente: .int ZonesAttente
iAdrZonesTemps: .int ZonesTemps
iAdrsBuffer: .int sBuffer
iAdrszCarriageReturn: .int szCarriageReturn
 
 
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} @ save registers
mov r2,#0 @ counter length */
1: @ loop length calculation
ldrb r1,[r0,r2] @ read octet start position + index
cmp r1,#0 @ if 0 its over
addne r2,r2,#1 @ else add 1 in the length
bne 1b @ and loop
@ so here r2 contains the length of the message
mov r1,r0 @ address message in r1
mov r0,#STDOUT @ code to write to the standard output Linux
mov r7, #WRITE @ code call system "write"
svc #0 @ call system
pop {r0,r1,r2,r7,lr} @ restaur registers
bx lr @ return
/******************************************************************/
/* Convert a string to a number stored in a registry */
/******************************************************************/
/* r0 contains the address of the area terminated by 0 or 0A */
/* r0 returns a number */
conversionAtoD:
push {fp,lr} @ save 2 registers
push {r1-r7} @ save others registers
mov r1,#0
mov r2,#10 @ factor
mov r3,#0 @ counter
mov r4,r0 @ save address string -> r4
mov r6,#0 @ positive sign by default
mov r0,#0 @ initialization to 0
1: /* early space elimination loop */
ldrb r5,[r4,r3] @ loading in r5 of the byte located at the beginning + the position
cmp r5,#0 @ end of string -> end routine
beq 100f
cmp r5,#0x0A @ end of string -> end routine
beq 100f
cmp r5,#' ' @ space ?
addeq r3,r3,#1 @ yes we loop by moving one byte
beq 1b
cmp r5,#'-' @ first character is -
moveq r6,#1 @ 1 -> r6
beq 3f @ then move on to the next position
2: /* beginning of digit processing loop */
cmp r5,#'0' @ character is not a number
blt 3f
cmp r5,#'9' @ character is not a number
bgt 3f
/* character is a number */
sub r5,#48
ldr r1,iMaxi @ check the overflow of the register
cmp r0,r1
bgt 99f @ overflow error
mul r0,r2,r0 @ multiply par factor 10
add r0,r5 @ add to r0
3:
add r3,r3,#1 @ advance to the next position
ldrb r5,[r4,r3] @ load byte
cmp r5,#0 @ end of string -> end routine
beq 4f
cmp r5,#0x0A @ end of string -> end routine
beq 4f
b 2b @ loop
4:
cmp r6,#1 @ test r6 for sign
moveq r1,#-1
muleq r0,r1,r0 @ if negatif, multiply par -1
b 100f
99: /* overflow error */
ldr r0,=szMessErrDep
bl affichageMess
mov r0,#0 @ return zero if error
100:
pop {r1-r7} @ restaur other registers
pop {fp,lr} @ restaur 2 registers
bx lr @return procedure
/* constante program */
iMaxi: .int 1073741824
szMessErrDep: .asciz "Too large: overflow 32 bits.\n"
.align 4
 
</syntaxhighlight>
 
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">time: to :integer input "Enter number of milliseconds: "
print "Sleeping..."
pause time
print "Awake!"</syntaxhighlight>
 
{{out}}
 
<pre>Enter number of milliseconds: 1000
Sleeping...
Awake!</pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">TrayTip, sleeping, sleeping
sleep, 2000 ; 2 seconds
TrayTip, awake, awake
Msgbox, awake</langsyntaxhighlight>
 
=={{header|AutoIt}}==
<langsyntaxhighlight AutoItlang="autoit">#AutoIt Version: 3.2.10.0
$sleep_me=InputBox("Sleep", "Number of seconds to sleep", "10", "", -1, -1, 0, 0)
Dim $sleep_millisec=$sleep_me*1000
MsgBox(0,"Sleep","Sleeping for "&$sleep_me&" sec")
sleep ($sleep_millisec)
MsgBox(0,"Awake","... Awaking")</langsyntaxhighlight>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f SLEEP.AWK [seconds]
BEGIN {
print("Sleeping...")
loop(ARGV[1])
print("Awake!")
exit(0)
}
function loop(seconds, t) {
# awk lacks a sleep mechanism, so simulate one by looping
t = systime()
while (systime() < t + seconds) {}
}
</syntaxhighlight>
<p>commands and output:</p>
<pre>
GAWK "BEGIN{print(strftime())}"
GAWK -f SLEEP.AWK 3
GAWK "BEGIN{print(strftime())}"
 
Wed Jan 16 18:06:44 Eastern Standard Time 2013
Sleeping...
Awake!
Wed Jan 16 18:06:47 Eastern Standard Time 2013
</pre>
 
=={{header|Axe}}==
The time unit for the Pause command is based on clock cycles, not seconds. At 15 MHz, one second is approximately equal to a value of 4500. At 6 MHz, one second is approximately 1800.
 
<syntaxhighlight lang="axe">Disp "TIME:"
input→A
0→T
length(A)→L
For(I,1,L)
If {A}<'0' or {A}>'9'
Disp "NOT A NUMBER",i
Return
End
T*10+{A}-'0'→T
A++
End
Disp "SLEEPING...",i
Pause T
Disp "AWAKE",i</syntaxhighlight>
 
=={{header|BASIC}}==
{{works with|QuickBasic|4.5}}
<langsyntaxhighlight lang="qbasic">INPUT sec 'the SLEEP command takes seconds
PRINT "Sleeping..."
SLEEP sec
PRINT "Awake!"</langsyntaxhighlight>
"SLEEP" with no argument will sleep until a button is pressed on the keyboard (including modifier keys such as shift or control). Also, pressing a key while SLEEP is waiting for a specific amount of time (as above) will end the SLEEP.
 
=== {{header|ZX Spectrum BasicBASIC256}} ===
<syntaxhighlight lang="basic256">print "Enter number of seconds to sleep: ";
input ms
print "Sleeping..."
pause ms
print "Awake!"
end</syntaxhighlight>
 
==={{header|True BASIC}}===
<syntaxhighlight lang="qbasic">PRINT "Enter number of seconds to sleep";
INPUT ms
PRINT "Sleeping..."
PAUSE ms
PRINT "Awake!"
END</syntaxhighlight>
 
==={{header|Yabasic}}===
The '''sleep-command''' has many different names: You may write <code>pause</code>, <code>sleep</code> or <code>wait</code> interchangeably; whatever you write, yabasic will always do exactly the same.
<syntaxhighlight lang="yabasic">input "Enter number of seconds to sleep: " ms
print "Sleeping..."
 
sleep ms
//pause ms
//wait ms
 
print "Awake!"
end</syntaxhighlight>
 
==={{header|Sinclair ZX81 BASIC}}===
The <code>PAUSE</code> statement pauses execution for a length of time expressed in terms of the frame rate of the television you are using as a monitor. But there are one or two problems with it...
 
(1) Televisions in different countries have (had) different frame rates, so a one-second pause would need to be coded as <code>PAUSE 50</code> in Britain and <code>PAUSE 60</code> in the United States. The use of <code>PAUSE</code> therefore reduces compatibility.
 
(2) The highest acceptable value is 32767 frames: anything higher is taken to mean "pause forever".
 
(3) If the user presses a key, the computer will stop pausing and resume execution from the line after the <code>PAUSE</code>.
 
(4) In <code>FAST</code> mode the <code>PAUSE</code> statement needs to be followed by <code>POKE 16437,255</code> to avoid corrupting the program.
 
(5) The duration of the pause is not terribly precise.
 
(6) The screen flickers irritatingly when the pause ends, even if you are in <code>SLOW</code> mode.
 
Bearing all these factors in mind, it will often be found easier to use an empty <code>FOR</code> loop instead.
 
(Oh, and the ZX81 character set doesn't include lower-case letters or an exclamation mark: so the message <tt>Awake!</tt> has to be replaced by <tt>AWAKE.</tt>)
 
<syntaxhighlight lang="basic">10 PRINT "HOW LONG SHOULD I SLEEP FOR?"
20 PRINT "(IN TELEVISION FRAMES)"
30 INPUT SLEEPTIME
40 PRINT "SLEEPING... ";
50 PAUSE SLEEPTIME
60 PRINT "AWAKE."</syntaxhighlight>
 
==={{header|BaCon}}===
 
<syntaxhighlight lang="freebasic">
'---The SLEEP command takes milliseconds by default but we will adjust it
PRINT "Enter a number for each second you want to wait\nthen press Enter "
INPUT millisec
PRINT "Sleeping..."
SLEEP millisec * 1000
PRINT "Awake!"
</syntaxhighlight>
 
==={{header|ZX Spectrum Basic}}===
 
Pressing a key will cut the pause short on the ZX Spectrum.
 
<syntaxhighlight lang="zxbasic">10 REM s is the number of seconds
20 LET s = 5
30 PRINT "Sleeping"
40 PAUSE s * 50
50 PRINT "Awake"</syntaxhighlight>
 
=={{header|Batch File}}==
Line 58 ⟶ 770:
 
{{works with|Windows NT|4}}
<langsyntaxhighlight lang="dos">@echo off
set /p Seconds=Enter the number of seconds to sleep:
set /a Seconds+=1
echo Sleeping ...
ping -n %Seconds% localhost >nul 2>&1
echo Awake!</langsyntaxhighlight>
A similar trick can be used to wait a certain number of milliseconds. The <code>ping</code> utility includes a <code>/w</code> option which specifies the timeout to wait for a reply. This coupled with an unreachable address (where the full timeout will be needed) leads to the following:
 
{{works with|Windows 2000}}
<langsyntaxhighlight lang="dos">@echo off
set /p MilliSeconds=Enter the number of milliseconds to sleep:
echo Sleeping ...
ping -n 1 -w %MilliSeconds% 1.2.3.4 >nul 2>&1
echo Awake!</langsyntaxhighlight>
 
Starting with Windows Vista there is a command-line utility to wait a number of seconds:
 
{{works with|Windows Vista}}
<langsyntaxhighlight lang="dos">@echo off
set /p Seconds=Enter the number of seconds to sleep:
echo Sleeping ...
timeout /t %Seconds% /nobreak >nul
echo Awake!</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<syntaxhighlight lang="bbcbasic"> INPUT "Enter the time to sleep in centiseconds: " sleep%
PRINT "Sleeping..."
WAIT sleep%
PRINT "Awake!"</syntaxhighlight>
Whilst sleeping BBC BASIC for Windows periodically tests for the ESCape key being pressed.
 
=={{header|C}}==
Line 88 ⟶ 808:
The function <tt>sleep</tt> needs seconds, which are read from the standard input.
 
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <unistd.h>
 
Line 99 ⟶ 819:
printf("Awake!\n");
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
 
<syntaxhighlight lang="csharp">using System;
using System.Threading;
 
class Program
{
static void Main(string[] args)
{
int sleep = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Sleeping...");
Thread.Sleep(sleep); //milliseconds
Console.WriteLine("Awake!");
}
}</syntaxhighlight>
 
=={{header|C++}}==
 
{{works with|C++11}}
<lang cpp>#include <unistd.h>
 
<syntaxhighlight lang="cpp">#include <iostream>
#include <thread>
#include <chrono>
int main()
{
unsigned long microseconds;
std::cin >> microseconds;
std::cout << "Sleeping..." << std::endl;
std::this_thread::sleep_for(std::chrono::microseconds(microseconds));
std::cout << "Awake!\n";
}
</syntaxhighlight>
 
{{works with|POSIX}}
 
<syntaxhighlight lang="cpp">#include <unistd.h>
#include <iostream>
 
Line 116 ⟶ 869:
cout << "Awake!" << endl;
return 0;
}</langsyntaxhighlight>
 
=={{header|CCaché sharp|C#ObjectScript}}==
<syntaxhighlight lang="caché objectscript">
 
SLEEP
<lang csharp>using System;
; the HANG command can use fractional seconds; the Awake line will be slightly off due to processing time
using System.Threading;
read "How long to sleep in seconds?: ",sleep
 
write !,"Sleeping... time is "_$ztime($piece($ztimestamp,",",2,2),1,2)
class Program
hang +sleep ; use + to cast numeric, if non-numeric will hang 0
{
write !,"Awake! Time is "_$ztime($piece($ztimestamp,",",2,2),1,2)
static void Main(string[] args)
{quit
</syntaxhighlight>
int sleep = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Sleeping...");
Thread.Sleep(sleep); //milliseconds
Console.WriteLine("Awake!");
}
}</lang>
 
{{out}}<pre>
SAMPLES>do ^SLEEP
How long to sleep in seconds?: 7.25
Sleeping... time is 14:48:29.27
Awake! Time is 14:48:36.55
</pre>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(defn sleep [ms] ; time in milliseconds
(println "Sleeping...")
(Thread/sleep ms)
(println "Awake!"))
; call it
(sleep 1000)</langsyntaxhighlight>
 
=={{header|COBOL}}==
COBOL 2023 introduced the <code>AFTER</code> phrase of the <code>CONTINUE</code> statement to specify a time period in seconds for which execution will be suspended, which, depending on implementation, could be not an integer.
{{works with|COBOL 2023}}
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. Sleep-In-Seconds.
 
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Seconds-To-Sleep USAGE IS FLOAT-LONG.
 
PROCEDURE DIVISION.
ACCEPT Seconds-To-Sleep
DISPLAY "Sleeping..."
CONTINUE AFTER Seconds-To-Sleep SECONDS
DISPLAY "Awake!"
GOBACK.
 
END PROGRAM Sleep-In-Seconds.</syntaxhighlight>
 
Prior to this there were two methods for putting the program to sleep using unofficial extensions.
 
The first expects the amount of time to be in seconds.
{{works with|ACUCOBOL-GT}}
{{works with|GnuCOBOL}}
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. Sleep-In-Seconds.
 
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Seconds-To-Sleep USAGE IS COMP-2.
*> Note: COMP-2, while supported on most implementations, is
*> non-standard. FLOAT-SHORT is the proper USAGE for Native
*> IEEE 754 Binary64 Floating-point data items.
 
PROCEDURE DIVISION.
ACCEPT Seconds-To-Sleep
DISPLAY "Sleeping..."
CALL "C$SLEEP" USING BY CONTENT Seconds-To-Sleep
DISPLAY "Awake!"
GOBACK.
 
END PROGRAM Sleep-In-Seconds.</syntaxhighlight>
 
While the second expects the time to be in nanoseconds. Note: Windows systems can only sleep to the nearest millisecond.
{{works with|GnuCOBOL}}
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. Sleep-In-Nanoseconds.
OPTIONS.
DEFAULT ROUNDED MODE IS NEAREST-AWAY-FROM-ZERO.
 
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Seconds-To-Sleep USAGE IS FLOAT-LONG.
01 Nanoseconds-To-Sleep USAGE IS FLOAT-LONG.
01 Nanoseconds-Per-Second CONSTANT AS 1000000000.
 
PROCEDURE DIVISION.
ACCEPT Seconds-To-Sleep
COMPUTE Nanoseconds-To-Sleep
= Seconds-To-Sleep * Nanoseconds-Per-Second
END-COMPUTE
 
DISPLAY "Sleeping..."
CALL "CBL_OC_NANOSLEEP"
USING BY CONTENT Nanoseconds-To-Sleep
END-CALL
 
DISPLAY "Awake!"
GOBACK.
 
END PROGRAM Sleep-In-Nanoseconds.</syntaxhighlight>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun test-sleep ()
(let ((seconds (read)))
(format t "Sleeping...~%")
Line 151 ⟶ 976:
(format t "Awake!~%")))
 
(test-sleep)</langsyntaxhighlight>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.cstdio, core.timethread;
 
import std.stdio;
import std.string;
void main() {
writef write("Enter a time(seconds) to sleep (in seconds): ");
 
writefln("Sleeping...");
long secs;
sleep(atoi(readln())*1000);
writefln readf("Awake! %d", &secs);
 
}</lang>
writeln("Sleeping...");
Thread.sleep(dur!"seconds"(secs));
writeln("Awake!");
}</syntaxhighlight>
{{out}}
<pre>Enter a time to sleep (in seconds): 5
Sleeping...
Awake!</pre>
 
=={{header|DCL}}==
<syntaxhighlight lang="dcl">$ amount_of_time = p1 ! hour[:[minute][:[second][.[hundredth]]]]
$ write sys$output "Sleeping..."
$ wait 'amount_of_time
$ write sys$output "Awake!"</syntaxhighlight>
{{out}}
<pre>$ @sleep 1 ! sleeps for 1 hour
Sleeping...
Awake!
$ @sleep 0:10 ! sleeps for 10 minutes
Sleeping...
Awake!
$ @sleep 0::10 ! sleeps for 10 seconds
Sleeping...
Awake!
$ @sleep 0:1:12 ! sleeps for 1 minute and 12 seconds
Sleeping...
Awake!
$ @sleep 23:59:59.99 ! sleeps for maximum amount of time
Sleeping...
Awake!</pre>
 
=={{header|DBL}}==
<syntaxhighlight lang="dbl">;
; Sleep for DBL version 4 by Dario B.
;
PROC
;------------------------------------------------------------------
XCALL FLAGS (0007000000,1) ;Suppress STOP message
OPEN(1,O,'TT:')
DISPLAY (1,"Sleeping...",10)
SLEEP 10 ;Sleep for 10 seconds
DISPLAY (1,"Awake!",10)
</syntaxhighlight>
 
=={{header|Delphi}}==
<syntaxhighlight lang="delphi">program SleepOneSecond;
 
{$APPTYPE CONSOLE}
 
uses SysUtils;
 
var
lTimeToSleep: Integer;
begin
if ParamCount = 0 then
lTimeToSleep := 1000
else
lTimeToSleep := StrToInt(ParamStr(1));
WriteLn('Sleeping...');
Sleep(lTimeToSleep); // milliseconds
WriteLn('Awake!');
end.</syntaxhighlight>
 
=={{header|Diego}}==
Diego is zero-threaded, meaning that the callee can handle the instruction how they wish (dependant on decision behaviour), however, the thread behaviour can be stipulated in code.
<syntaxhighlight lang="diego">begin_instuct(sleepTime);
ask_human()_first()_msg(Enter number of seconds to sleep: )_var(sleepSecs)_me();
set_decision(asynchronous)_me();
me_msg(Sleeping...);
me_sleep[sleepSecs]_unit(secs);
me_msg(Awake!);
reset_decision()_me();
end_instruct(sleepTime);
 
exec_instruct(sleepTime)_me();
</syntaxhighlight>
 
=={{header|DIBOL-11}}==
<syntaxhighlight lang="dibol-11">
 
START ;Demonstrate the SLEEP function
 
RECORD SLEEPING
, A8, "Sleeping"
 
RECORD WAKING
, A6,"Awake"
 
PROC
XCALL FLAGS (0007000000,1) ;Suppress STOP message
 
OPEN(8,O,'TT:')
WRITES(8,SLEEPING)
SLEEP 30 ; Sleep for 30 seconds
WRITES(8,WAKING)
 
END
 
 
</syntaxhighlight>
=={{header|E}}==
 
Line 172 ⟶ 1,096:
So, the closest thing possible to the task description is to wait for the specified time to pass, then do whatever the next thing is.
 
<langsyntaxhighlight lang="e">def sleep(milliseconds :int, nextThing) {
stdout.println("Sleeping...")
timer.whenPast(timer.now() + milliseconds, fn {
Line 178 ⟶ 1,102:
nextThing()
})
}</langsyntaxhighlight>
 
=={{header|EasyLang}}==
<syntaxhighlight lang="easylang">
print "How many seconds should I sleep? "
sec = number input
print "Sleeping ..."
sleep sec
print "Awake!"
</syntaxhighlight>
 
=={{header|EGL}}==
<syntaxhighlight lang="egl">program Sleep type BasicProgram{}
 
// Syntax: sysLib.wait(time BIN(9,2) in)
 
function main()
SysLib.writeStdout("Sleeping!");
sysLib.wait(15); // waits for 15 seconds
SysLib.writeStdout("Awake!");
end
 
end</syntaxhighlight>
 
=={{header|Eiffel}}==
Line 186 ⟶ 1,132:
<code lang="eiffel">sleep</code> takes an argument which declares the number of nanoseconds to suspend the thread's execution.
 
<langsyntaxhighlight lang="eiffel ">class
APPLICATION
inherit
Line 202 ⟶ 1,148:
print ("Awake!%N")
end
end</langsyntaxhighlight>
 
Output (sleeping 10 seconds):
<pre>
Enter a number of nanoseconds: 10000000000
Sleeping...
Awake!
</pre>
 
=={{header|Elena}}==
ELENA 4.x :
<syntaxhighlight lang="elena">import extensions;
public program()
{
int sleep := console.readLine().toInt();
console.printLine("Sleeping...");
system'threading'threadControl.sleep(sleep);
console.printLine("Awake!")
}</syntaxhighlight>
 
=={{header|Elixir}}==
<syntaxhighlight lang="elixir">sleep = fn seconds ->
IO.puts "Sleeping..."
:timer.sleep(1000 * seconds) # in milliseconds
IO.puts "Awake!"
end
 
sec = if System.argv==[], do: 1, else: hd(System.argv) |> String.to_integer
sleep.(sec)</syntaxhighlight>
 
=={{header|Emacs Lisp}}==
<syntaxhighlight lang="lisp">(let ((seconds (read-number "Time in seconds: ")))
(message "Sleeping ...")
(sleep-for seconds)
(message "Awake!"))</syntaxhighlight>
 
The time can be a decimal like 1.5 though the actual resolution of <code>sleep-for</code> depends on the operating system. The similar <code>sit-for</code> stops sleeping if there's pending keyboard input.
 
=={{header|EMal}}==
<syntaxhighlight lang="emal">
^|The pause command takes milliseconds, we adjust to seconds|^
fun main = int by List args
int seconds
if args.length == 1 do seconds = int!args[0] end
if seconds == 0
seconds = ask(int, "Enter number of seconds to sleep: ")
end
writeLine("Sleeping...")
pause(1000 * seconds)
writeLine("Awake!")
return 0
end
exit main(Runtime.args)
</syntaxhighlight>
{{out}}
Sample session:
<pre>
Enter number of seconds to sleep: 7
Sleeping...
Awake!
Line 214 ⟶ 1,214:
 
Erlang doesn't really have such a thing as a main thread. However, sleeping any process can be done with the <tt>timer:sleep/1</tt> function:
<langsyntaxhighlight lang="erlang">main() ->
io:format("Sleeping...~n"),
timer:sleep(1000), %% in milliseconds
io:format("Awake!~n").</langsyntaxhighlight>
 
It is to be noted that Erlang's sleep function is implemented in Erlang with a timeout on a <tt>receive</tt>, so you may sometimes encounter the following way of sleeping a process:
<langsyntaxhighlight lang="erlang">main() ->
io:format("Sleeping...~n"),
receive
after 1000 -> ok %% in milliseconds
end,
io:format("Awake!~n").</langsyntaxhighlight>
 
which is the way it is implemented in the <tt>timer</tt> module.
 
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
..............
INPUT("Enter the time to sleep in seconds: ";sleep)
PRINT("Sleeping...")
PAUSE(sleep)
PRINT("Awake!")
..............
</syntaxhighlight>
 
=={{header|F_Sharp|F#}}==
{{trans|C#}}
<syntaxhighlight lang="fsharp">open System
open System.Threading
[<EntryPoint>]
let main args =
let sleep = Convert.ToInt32(Console.ReadLine())
Console.WriteLine("Sleeping...")
Thread.Sleep(sleep); //milliseconds
Console.WriteLine("Awake!")
0</syntaxhighlight>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: calendar io math.parser threads ;
 
: read-sleep ( -- )
Line 236 ⟶ 1,259:
"Sleeping..." print
sleep
"Awake!" print ;</langsyntaxhighlight>
 
=={{header|Fantom}}==
 
Fantom has a 'Duration' class, which uses time definitions with units: e.g., 5sec, 100ns, 5hr. These are used for input in the following program.
 
<syntaxhighlight lang="fantom">
using concurrent
 
class Main
{
public static Void main ()
{
echo ("Enter a time to sleep: ")
input := Env.cur.in.readLine
try
{
time := Duration.fromStr (input)
echo ("sleeping ...")
Actor.sleep (time)
echo ("awake!")
}
catch
{
echo ("Invalid time entered")
}
}
}
</syntaxhighlight>
 
Output:
<pre>
Enter a time to sleep:
5sec
sleeping ...
awake!
</pre>
 
=={{header|FBSL}}==
<syntaxhighlight lang="qbasic">#APPTYPE CONSOLE
DIM %msec
PRINT "Milliseconds to sleep: ";
%msec = FILEGETS(stdin, 10)
PRINT "Sleeping..."
SLEEP(%msec)
PRINT "Awake!"
PAUSE
</syntaxhighlight>
Output
<pre>Milliseconds to sleep: 1000
Sleeping...
Awake!
 
Press any key to continue...</pre>
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">: sleep ( ms -- )
." Sleeping..."
ms
." awake." cr ;</langsyntaxhighlight>
 
====Explanation note on MS====
 
MS ( n -- ) A.10.6.2.1905
 
MS is a Standard Forth word that waits for at least n milliseconds. It is part of the optional Facility Wordset. It is more than just a simple delay in that in a multi-tasking environment when MS is executed the current task is asleep until the time expires.
 
=={{header|Fortran}}==
<langsyntaxhighlight lang="fortran">program test_sleep
 
implicit none
Line 261 ⟶ 1,344:
end if
 
end program test_sleep</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Dim ms As UInteger
Input "Enter number of milliseconds to sleep" ; ms
Print "Sleeping..."
Sleep ms, 1 '' the "1" means Sleep can't be interrupted with a keystroke
Print "Awake!"
End</syntaxhighlight>
 
Sample input/output
{{out}}
<pre>
Enter number of milliseconds to sleep? 3000
Sleeping...
Awake!
</pre>
 
=={{header|Frink}}==
In Frink, all values have units of measure, and sleep functions take units of time, which can be seconds, nanoseconds, minutes, hours, etc. The user may enter values like "3 hours" or "1 ms". The units of measure are captured as first-class values in the language, and not hidden in comments nor implied in APIs.
<syntaxhighlight lang="frink">
do
t = eval[input["Enter amount of time to sleep: ", "1 second"]]
while ! (t conforms time)
 
println["Sleeping..."]
sleep[t]
println["Awake!"]
</syntaxhighlight>
 
=={{header|Go}}==
Technically, this varies from the task by sleeping the main ''goroutine'' rather than the main ''thread''. The Go runtime multiplexes goroutines to operating system threads and the language does not provide direct access to threads.
time.Sleep takes a number of nanoseconds, but the actual resolution is system-dependent.
<langsyntaxhighlight lang="go">package main
 
import "time"
Line 271 ⟶ 1,384:
 
func main() {
fmt.Print("Enter number of seconds to sleep: ")
var ns int64
var sec float64
fmt.Scanf("%d", &ns)
fmt.Scanf("%f", &sec)
fmt.Print("Sleeping…")
time.Sleep(nstime.Duration(sec * float64(time.Second)))
fmt.Println("Awake\nAwake!")
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
Solution:
<syntaxhighlight lang="groovy">def sleepTest = {
println("Sleeping...")
sleep(it)
println("Awake!")
}</syntaxhighlight>
 
Test:
<syntaxhighlight lang="groovy">sleepTest(1000)
print '''
Hmmm. That was... less than satisfying.
How about this instead?
'''
Thread.start {
(0..5).each {
println it
sleep(1000)
}
}
sleepTest(5000)</syntaxhighlight>
 
Output:
<pre>Sleeping...
Awake!
 
Hmmm. That was... less than satisfying
How about this instead?
Sleeping...
0
1
2
3
4
Awake!
5</pre>
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Control.Concurrent
 
main = do seconds <- readLn
putStrLn "Sleeping..."
threadDelay $ round $ seconds * 1000000
putStrLn "Awake!"</langsyntaxhighlight>
 
=={{header|HicEst}}==
<langsyntaxhighlight lang="hicest">DLG(NameEdit = milliseconds, Button = "Go to sleep")
WRITE(StatusBar) "Sleeping ... "
SYSTEM(WAIT = milliseconds)
WRITE(Messagebox) "Awake!"</langsyntaxhighlight>
 
=={{header|IDLIcon}} and {{header|Unicon}}==
<syntaxhighlight lang="icon">procedure main()
 
<lang IDL>
read,i,prompt='Input sleep time in seconds: '
print,'Sleeping...'
wait,i ; in seconds, but accepts floats(/fractional) as input
print,'Awake!'
</lang>
 
== Icon and Unicon ==
==={{header|Icon}}===
<lang Icon>procedure main()
 
repeat {
Line 314 ⟶ 1,455:
delay(1000 * s)
write("Awake!")
end</langsyntaxhighlight>
 
==={{header|Unicon}}===
=={{header|IDL}}==
This Icon solution works in Unicon.
 
<syntaxhighlight lang="idl">
read,i,prompt='Input sleep time in seconds: '
print,'Sleeping...'
wait,i ; in seconds, but accepts floats(/fractional) as input
print,'Awake!'
</syntaxhighlight>
 
=={{header|J}}==
 
'''Solution''':
<langsyntaxhighlight lang="j">sleep =: 6!:3
 
sleeping=: monad define
Line 327 ⟶ 1,475:
sleep y
smoutput 'Awake!'
)</langsyntaxhighlight>
 
'''Example''':
<langsyntaxhighlight lang="j"> sleeping 0.500 NB. Sleep 500 milliseconds
Sleeping...
Awake!</langsyntaxhighlight>
 
=={{header|Java}}==
{{works with|Java|1.5+}}
<lang java>import java.util.Scanner;
<syntaxhighlight lang="java5">
import java.util.InputMismatchException;
import java.util.Scanner;
 
public class Sleep {
public static void main(final String[] args) throws InterruptedException {
try {
Scanner input = new Scanner(System.in);
int ms = inputnew Scanner(System.in).nextInt(); //Java's sleep method accepts milliseconds
System.out.println("Sleeping...");
Thread.sleep(ms);
System.out.println("Awake!");
} catch (InputMismatchException inputMismatchException) {
}
System.err.println("Exception: " + inputMismatchException);
}</lang>
}
}
}</syntaxhighlight>
 
===Using Java 8===
=={{header|JavaScript}} (in a web browser)==
<syntaxhighlight lang="java">
import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
 
public final class Sleep {
public static void main(String[] args) {
try {
System.out.println("Enter time to sleep in milliseconds:");
Scanner scanner = new Scanner(System.in);
final int delay = scanner.nextInt();
scanner.close();
System.out.println("Sleeping...");
TimeUnit.MILLISECONDS.sleep(delay);
System.out.println("Awake!");
} catch (InputMismatchException | InterruptedException exception) {
exception.printStackTrace(System.err);;
}
}
}
</syntaxhighlight>
{{ out }}
<pre>
Enter time to sleep in milliseconds:
4321
Sleeping...
Awake!
 
</pre>
 
=={{header|JavaScript}}==
===(in a web browser)===
 
Generally, JavaScript in a web browser is event-loop based and (except for alert()) non-blocking. So, the closest thing possible to the task description is to do something once the specified time has passed.
 
<syntaxhighlight lang="html"><script>
<lang html><html><head><title>RC Sleep The Main Thread</title></head><body>
 
<form>
setTimeout(function () {
<button type="button" onclick="
function document.write(s'Awake!') {
}, prompt("Number of milliseconds to sleep"));
var l = document.getElementById('log');
 
l.appendChild(document.createTextNode(''+s));
l.appendChild(document.createElementwrite('brSleeping... '));
 
}
</script></syntaxhighlight>
 
write('Sleeping...');
=={{header|jq}}==
setTimeout(function () {
 
write('Awake!');
`sleep($n)` will pause (busily) for at least the given time period, measured in seconds.
}, parseFloat(document.getElementById('delay').value));
The excess time slept, namely `$n | sleep(.) - .`, will likely be less than some particular value on each platform, e.g. 0.00001 seconds on a 3GHz machine.
<syntaxhighlight lang="jq">
">Sleep</button> for <input id="delay"> milliseconds.
# Pseudosleep for at least the given number of $seconds (a number)
</form>
# and emit the actual number of seconds that have elapsed.
<pre id="log"></pre>
def sleep($seconds):
</body></html></lang>
now
| . as $now
| until( . - $now >= $seconds; now)
| . - $now ;
</syntaxhighlight>
 
=={{header|Jsish}}==
<syntaxhighlight lang="javascript">/*
Sleep, in Jsish
*/
 
printf('Sleep time (in milliseconds)? ');
var ms = parseInt(console.input());
 
puts('Sleeping...');
sleep(ms);
puts('Awake!');</syntaxhighlight>
 
=={{header|Julia}}==
 
<syntaxhighlight lang="julia">
print("Please enter sleep duration in seconds: ")
input = int(readline(STDIN))
println("Sleeping...")
sleep(input)
println("Awake!")
</syntaxhighlight>
 
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">// version 1.0.6
 
fun main(args: Array<String>) {
print("Enter number of milliseconds to sleep: ")
val ms = readLine()!!.toLong()
println("Sleeping...")
Thread.sleep(ms)
println("Awake!")
}</syntaxhighlight>
Sample input/output:
{{out}}
<pre>
Enter number of milliseconds to sleep: 3000
Sleeping...
Awake!
</pre>
 
=={{header|LabVIEW}}==
Uses milliseconds. LabVIEW has no "main thread" so it must be forced with a sequence structure.
<br/>{{VI snippet}}<br/>
[[File: Sleep.png]]
 
=={{header|Lang}}==
<syntaxhighlight lang="lang">
$ms = fn.long(fn.input())
fn.println(Sleeping...)
fn.sleep($ms)
fn.println(Awake!)
</syntaxhighlight>
 
=={{header|Lasso}}==
Lasso has a built in sleep command that accepts milliseconds as an input.
 
<syntaxhighlight lang="lasso">stdoutnl('Sleeping...')
sleep(5000) // Sleep 5 seconds
stdoutnl('Awake!')</syntaxhighlight>
 
=={{header|Lhogho}}==
The Logo version works without modification. Another way to Sleep, in the Windows version of Lhogho, is to use the Win32 function, viz
<syntaxhighlight lang="logo">make "Void "V0
make "Long "U4
make "kernel32_handle libload "kernel32.dll
to Sleep :dwMilliseconds
end
external "Sleep [ Void Sleep Long] :kernel32_handle
 
to millisleep :n
print [Sleeping...]
Sleep :n ; units: 1/1000th of a second
print [Awake.]
end</syntaxhighlight>
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">Input "Please input the number of milliseconds you would like to sleep. "; sleeptime
Print "Sleeping..."
CallDLL #kernel32, "Sleep", sleeptime As long, ret As void
Print "Awake!"
</syntaxhighlight>
 
=={{header|Lingo}}==
{{libheader|CommandLine Xtra}}
<syntaxhighlight lang="lingo">on doSleep (ms)
put "Sleeping..."
sleep(ms)
put "Awake!"
end</syntaxhighlight>
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">
to sleep :n
print [Sleeping...]
Line 377 ⟶ 1,661:
print [Awake.]
end
</syntaxhighlight>
</lang>
 
=={{header|MATLABLogtalk}}==
Works when using SWI-Prolog, XSB, or YAP as the backend compilers:
<lang MATLAB>function sleep()
<syntaxhighlight lang="logtalk">
:- object(sleep).
 
:- public(how_long/1).
 
how_long(Seconds) :-
write('Sleeping ...'), nl,
thread_sleep(Seconds),
write('... awake!'), nl.
 
:- end_object.
</syntaxhighlight>
Sample output:
<syntaxhighlight lang="text">
| ?- sleep::how_long(5).
Sleeping ...
... awake!
yes
</syntaxhighlight>
 
=={{header|Lua}}==
{{libheader|LuaSocket}}
The input does not need to be a whole number, eg. "0.5" would cause the program to wait for half a second.
<syntaxhighlight lang="lua">local socket = require("socket")
io.write("Input a number of seconds to sleep: ")
local input = io.read("*number")
print("Sleeping")
socket.sleep(input)
print("Awake!")</syntaxhighlight>
A similar effect could be achieved using a "busy" loop but the function in lua-socket is gentler on your CPU.
 
=={{header|M2000 Interpreter}}==
Statement Wait pause the current thread but other threads from module (not in this example) may run.
<syntaxhighlight lang="m2000 interpreter">
Module CheckIt {
Input "Input a number of milliseconds to sleep:", N
Print "Sleeping..."
Wait N
Print "Awake"
}
CheckIt
</syntaxhighlight>
 
=={{header|Maple}}==
<syntaxhighlight lang="maple">sleep := proc(secs)
print("Sleeping...");
Threads:-Sleep(secs);
print("Awake!");
end proc:</syntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
This function, as you can probably guess, takes its argument in seconds.
While this function does tie up execution (but not with a busy wait), the Mathematica front end remains fully functional and can be used to stop the sleeping with Evaluation -> Abort Evaluation.
<syntaxhighlight lang="mathematica">Sleep[seconds_] := (Print["Sleeping..."]; Pause[seconds]; Print["Awake!"];)</syntaxhighlight>
 
=={{header|MATLAB}} / {{header|Octave}}==
<syntaxhighlight lang="matlab">function sleep()
 
time = input('How many seconds would you like me to sleep for? ');
Line 388 ⟶ 1,729:
disp('Awake!');
end</langsyntaxhighlight>
 
=={{header|Objective-Cmin}}==
{{works with|min|0.19.6}}
Of course the same code of [[Sleep#C]] works for Objective-C. The following code uses a OpenStep derived framework (Cocoa, GNUstep...).
<syntaxhighlight lang="min">"Enter number of milliseconds to sleep" ask int
"Sleeping..." puts!
sleep
"Awake!" puts!</syntaxhighlight>
 
=={{header|Nanoquery}}==
{{works with|GNUstep}} and {{works with|Cocoa}}
<syntaxhighlight lang="nanoquery">time = int(input("time to sleep (ms): "))
 
println "Sleeping..."
<lang objc>#import <Foundation/Foundation.h>
sleep(time)
println "Awake!"</syntaxhighlight>
 
=={{header|Nemerle}}==
int main()
<syntaxhighlight lang="nemerle">using System;
using System.Console;
using System.Threading.Thread; // this is where the Sleep() method comes from
 
module Zzzz
{
Main() : void
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
{
NSTimeInterval sleeptime;
def nap_time = Int32.Parse(ReadLine());
WriteLine("Sleeping...");
Sleep(nap_time); // parameter is time in milliseconds
WriteLine("Awake!");
}
}</syntaxhighlight>
 
=={{header|NetRexx}}==
printf("wait time in seconds: ");
<syntaxhighlight lang="netrexx">/* NetRexx */
scanf("%f", &sleeptime);
options replace format comments java crossref symbols nobinary
 
runSample(arg)
NSLog(@"sleeping...");
return
[NSThread sleepForTimeInterval: sleeptime];
NSLog(@"awakening...");
 
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[pool release];
method sleep(secs) public static binary
return 0;
ms = (secs * 1000).format(null, 0) -- milliseconds, rounded to nearest integer
}</lang>
say 'Sleeping...'
do
Thread.sleep(ms)
catch ix = InterruptedException
say 'Sleep interrupted!'
ix.printStackTrace()
end
say 'Awake!'
return
 
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) public static
secs = -1
loop until \secs.datatype('N')
if secs > 0 then do
say 'Napping for' secs's'
say
sleep(secs)
end
say
say 'How many seconds do you want me to sleep? (enter something non-numeric to terminate)\-'
parse ask secs .
say
end
say
say 'Goodbye...'
say
return
</syntaxhighlight>
 
=={{header|NewLISP}}==
<syntaxhighlight lang="newlisp">(println "Sleeping..." )
(sleep 2000) ; Wait for 2 seconds
(println "Awake!")</syntaxhighlight>
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">import os, strutils
 
echo "Enter how long I should sleep (in milliseconds):"
var timed = stdin.readLine.parseInt()
echo "Sleeping..."
sleep timed
echo "Awake!"</syntaxhighlight>
 
=={{header|NS-HUBASIC}}==
The <code>PAUSE</code> statement pauses execution for a length of time expressed in terms of the frame rate of the television you are using as a monitor.
<syntaxhighlight lang="ns-hubasic">10 PRINT "I'LL TELL YOU WHEN I BECOME AWAKE AGAIN..."
20 PAUSE 100
30 PRINT "NOW I'M AWAKE AGAIN."</syntaxhighlight>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
bundle Default {
class Test {
function : Main(args : System.String[]) ~ Nil {
if(args->Size() = 1) {
ms := args[0]->ToInt();
ms->PrintLine();
"Sleeping..."->PrintLine();
Thread->Sleep(msargs[0]->ToInt());
"Awake!"->PrintLine();
};
Line 428 ⟶ 1,834:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Objective-C}}==
Of course the same code of [[Sleep#C]] works for Objective-C. The following code uses a OpenStep derived framework (Cocoa, GNUstep...).
 
{{works with|GNUstep}} and {{works with|Cocoa}}
 
<syntaxhighlight lang="objc">#import <Foundation/Foundation.h>
 
int main()
{
@autoreleasepool {
 
NSTimeInterval sleeptime;
printf("wait time in seconds: ");
scanf("%f", &sleeptime);
 
NSLog(@"sleeping...");
[NSThread sleepForTimeInterval: sleeptime];
NSLog(@"awakening...");
 
}
return 0;
}</syntaxhighlight>
 
=={{header|OCaml}}==
 
<langsyntaxhighlight lang="ocaml">#load "unix.cma";;
let seconds = read_int ();;
print_endline "Sleeping...";;
Unix.sleep seconds;; (* number is integer in seconds *)
print_endline "Awake!";;</langsyntaxhighlight>
 
or
<langsyntaxhighlight lang="ocaml">#load "unix.cma";;
#directory "+threads";;
#load "threads.cma";;
Line 445 ⟶ 1,874:
print_endline "Sleeping...";;
Thread.delay seconds;; (* number is in seconds ... but accepts fractions *)
print_endline "Awake!";;</langsyntaxhighlight>
 
=={{header|Oforth}}==
<syntaxhighlight lang="oforth"> : sleepMilli(n) "Sleeping..." . n sleep "Awake!" println ;</syntaxhighlight>
 
=={{header|ooRexx}}==
<syntaxhighlight lang="oorexx">Say time()
Call sysSleep 10 -- wait 10 seconds
Say time()</syntaxhighlight>
{{out}}
<pre>14:23:40
14:23:50</pre>
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">declare
class TextFile from Open.file Open.text end
StdIn = {New TextFile init(name:stdin)}
Line 455 ⟶ 1,895:
{System.showInfo "Sleeping..."}
{Delay WaitTime} %% in milliseconds
{System.showInfo "Awake!"}</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
{{works with|PARI/GP|2.4.3 and above on Linux}}
GP does not have threading built in and so cannot truly sleep; this is code for spin-idling.
 
<lang>sleep(s)={
===gettime===
The units are milliseconds.
<syntaxhighlight lang="parigp">sleep(ms)={
print("Sleeping...");
while((ms-=gettime()) > 0,);
print("Awake!")
};
 
sleep(input())</syntaxhighlight>
 
===alarm===
{{works with|PARI/GP|2.4.3 and above on Linux}}
The units are seconds.
<syntaxhighlight lang="parigp">sleep(s)={
print("Sleeping...");
alarm(s);
Line 467 ⟶ 1,920:
};
 
sleep(input())</langsyntaxhighlight>
 
=={{header|Pascal}}==
See [[Sleep#Delphi | Delphi]]
 
=={{header|Peloton}}==
Literate mode
<syntaxhighlight lang="sgml"><@ SAYLIT>Number of seconds: </@><@ GETVAR>secs</@>
<@ SAYLIT>Sleeping</@>
<@ ACTPAUVAR>secs</@>
<@ SAYLIT>Awake</@></syntaxhighlight>
 
French variable-length opcodes
<syntaxhighlight lang="sgml"><# MontrezLittéralement>Number of seconds: </#><# PrenezUneValeurVariable>secs</#>
<# MontrezLittéralement>Sleeping</#>
<# AgissezFaireUnePauseVariable>secs</#>
<# MontrezLittéralement>Awake</#></syntaxhighlight>
 
(Simplified) Chinese fixed-length opcodes
<syntaxhighlight lang="sgml"><@ 显示_字串_>Number of seconds: </@><@ 获取_变量_>secs</@>
<@ 显示_字串_>Sleeping</@>
<@ 运行_暂停动变量_>secs</@>
<@ 显示_字串_>Awake</@></syntaxhighlight>
 
=={{header|Perl}}==
 
seconds:
<langsyntaxhighlight lang="perl">$seconds = <>;
print "Sleeping...\n";
sleep $seconds; # number is in seconds
print "Awake!\n";</langsyntaxhighlight>
 
microseconds and nanoseconds using the Time::HiRes module:
<langsyntaxhighlight lang="perl">use Time::HiRes qw( usleep nanosleep );
 
$microseconds = <>;
Line 488 ⟶ 1,963:
print "Sleeping...\n";
nanosleep $nanoseconds;
print "Awake!\n";</langsyntaxhighlight>
 
It's also possible to sleep for fractional seconds by abusing the select function:
=={{header|Perl 6}}==
<syntaxhighlight lang="perl">say "Sleeping...";
select undef, undef, undef, 0.5;
say "Awake!";</syntaxhighlight>
 
=={{header|Phix}}==
The <tt>sleep</tt> function argument is in units of seconds, but these may be fractional (to the limits of your system's clock).
{{libheader|Phix/basics}}
 
<!--<syntaxhighlight lang="phix">-->
<lang perl6>my $sec = prompt("Sleep for how many microfortnights? ") * 1.2096;
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (prompt_number, sleep)</span>
say "Sleeping...";
<span style="color: #004080;">atom</span> <span style="color: #000000;">a</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">prompt_number</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"wait for duration (in seconds, 0..20):"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">20</span><span style="color: #0000FF;">})</span>
sleep $sec;
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Sleeping...\n"</span><span style="color: #0000FF;">)</span>
say "Awake!";</lang>
<span style="color: #7060A8;">sleep</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">)</span>
 
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Awake!\n"</span><span style="color: #0000FF;">)</span>
Note that 1.2096 is a rational number in Perl&nbsp;6, not floating point, so precision can be maintained even when dealing with very small powers of ten.
<!--</syntaxhighlight>-->
Note that sleep() is entirely inappropriate for GUI applications, which should instead set a routine to resume processing
(that would be timer_cb below), activate a timer (set RUN to true), and relinquish control to the event loop. Another
excellent way to perform extended processing without making an application unresponsive is via an IDLE_ACTION, provided
that also regularly relinquishes control to the event loop, and can pick up where it left off when next invoked.
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">-- demo\rosetta\sleep.exw</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">include</span> <span style="color: #000000;">pGUI</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #004080;">Ihandle</span> <span style="color: #000000;">dlg</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">state</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">label</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">slider</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">snooze</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">timer</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">timer_cb</span><span style="color: #0000FF;">(</span><span style="color: #004080;">Ihandle</span> <span style="color: #000080;font-style:italic;">/*timer*/</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupSetAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">state</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"TITLE"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"awake"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupSetInt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">timer</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"RUN"</span><span style="color: #0000FF;">,</span><span style="color: #004600;">false</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #004600;">IUP_CONTINUE</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">slider_cb</span><span style="color: #0000FF;">(</span><span style="color: #004080;">Ihandle</span> <span style="color: #000080;font-style:italic;">/*slider*/</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">v</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupGetDouble</span><span style="color: #0000FF;">(</span><span style="color: #000000;">slider</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"VALUE"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupSetInt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">timer</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"TIME"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">v</span><span style="color: #0000FF;">*</span><span style="color: #000000;">1000</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupSetStrAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">label</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"TITLE"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%3.1fs"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">v</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">return</span> <span style="color: #004600;">IUP_CONTINUE</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">snooze_cb</span><span style="color: #0000FF;">(</span><span style="color: #004080;">Ihandle</span> <span style="color: #000080;font-style:italic;">/*snooze*/</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupSetAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">state</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"TITLE"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"asleep"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupSetInt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">timer</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"RUN"</span><span style="color: #0000FF;">,</span><span style="color: #004600;">true</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #004600;">IUP_CONTINUE</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #7060A8;">IupOpen</span><span style="color: #0000FF;">()</span>
<span style="color: #000000;">state</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupLabel</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"awake"</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">label</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupLabel</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"2.0s"</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">slider</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupValuator</span><span style="color: #0000FF;">(</span><span style="color: #004600;">NULL</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"VALUECHANGED_CB"</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"slider_cb"</span><span style="color: #0000FF;">),</span><span style="color: #008000;">"MIN=1, MAX=15, VALUE=2, EXPAND=HORIZONTAL"</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">snooze</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupButton</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Snooze"</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"snooze_cb"</span><span style="color: #0000FF;">),</span><span style="color: #008000;">"EXPAND=HORIZONTAL"</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">dlg</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupDialog</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">IupVbox</span><span style="color: #0000FF;">({</span><span style="color: #7060A8;">IupHbox</span><span style="color: #0000FF;">({</span><span style="color: #7060A8;">IupLabel</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"state: "</span><span style="color: #0000FF;">),</span><span style="color: #000000;">state</span><span style="color: #0000FF;">},</span><span style="color: #008000;">"ALIGNMENT=ACENTER"</span><span style="color: #0000FF;">),</span>
<span style="color: #7060A8;">IupHbox</span><span style="color: #0000FF;">({</span><span style="color: #7060A8;">IupLabel</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Duration: "</span><span style="color: #0000FF;">),</span><span style="color: #000000;">label</span><span style="color: #0000FF;">,</span><span style="color: #000000;">slider</span><span style="color: #0000FF;">},</span><span style="color: #008000;">"ALIGNMENT=ACENTER"</span><span style="color: #0000FF;">),</span>
<span style="color: #7060A8;">IupHbox</span><span style="color: #0000FF;">({</span><span style="color: #000000;">snooze</span><span style="color: #0000FF;">})},</span>
<span style="color: #008000;">"MARGIN=10x10"</span><span style="color: #0000FF;">),</span>
<span style="color: #008000;">`TITLE="Snooze"`</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupSetAttributeHandle</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"STARTFOCUS"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">snooze</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">timer</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupTimer</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"timer_cb"</span><span style="color: #0000FF;">),</span><span style="color: #000000;">2000</span><span style="color: #0000FF;">,</span><span style="color: #004600;">false</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupShow</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()!=</span><span style="color: #004600;">JS</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">IupMainLoop</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">IupClose</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--</syntaxhighlight>-->
 
=={{header|PHP}}==
 
seconds:
<langsyntaxhighlight lang="php">$seconds = 42;
echo "Sleeping...\n";
sleep($seconds); # number is integer in seconds
echo "Awake!\n";</langsyntaxhighlight>
 
microseconds:
<langsyntaxhighlight lang="php">$microseconds = 42000000;
echo "Sleeping...\n";
usleep($microseconds); # number is integer in microseconds
echo "Awake!\n";</langsyntaxhighlight>
 
nanoseconds:
<langsyntaxhighlight lang="php">$nanoseconds = 42000000000;
echo "Sleeping...\n";
time_nanosleep($seconds, $nanoseconds); # first arg in seconds plus second arg in nanoseconds
echo "Awake!\n";</langsyntaxhighlight>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(prinl "Sleeping..." )
(wait 2000) # Wait for 2 seconds
(prinl "Awake!")</langsyntaxhighlight>
As [http://software-lab.de/doc/refW.html#wait wait] will continue executing
background events, another possibility (for a complete stop) is calling
some external program like
<langsyntaxhighlight PicoLisplang="picolisp">(prinl "Sleeping..." )
(call 'sleep 2) # Wait for 2 seconds
(prinl "Awake!")</langsyntaxhighlight>
 
=={{header|Pike}}==
<syntaxhighlight lang="pike">int main() {
int seconds = (int)Stdio.stdin->gets();
write("Sleeping...\n");
sleep(seconds);
write("Awake!\n");
return 0;
}</syntaxhighlight>
 
=={{header|Pixilang}}==
<syntaxhighlight lang="pixilang">fputs("Sleeping...\n")
sleep(1000)
fputs("Awake!\n")</syntaxhighlight>
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
put ('sleeping');
delay (2000); /* wait for 2 seconds (=2000 milliseconds). */
put ('awake');
</syntaxhighlight>
</lang>
 
=={{header|Plain English}}==
<syntaxhighlight lang="plainenglish">To run:
Start up.
Demonstrate waiting.
Wait for the escape key.
Shut down.
 
To demonstrate waiting:
Write "How many milliseconds should I wait? " to the console without advancing.
Read some milliseconds from the console.
Write "Sleeping..." to the console.
Wait for the milliseconds.
Write "Awake!" to the console.</syntaxhighlight>
 
=={{header|PowerShell}}==
<langsyntaxhighlight lang="powershell">$d = [int] (Read-Host Duration in seconds)
Write-Host Sleeping ...
Start-Sleep $d
Write-Host Awake!</langsyntaxhighlight>
The <code>-Milliseconds</code> parameter to <code>Start-Sleep</code> can be used to allow for sub-second precision in sleeping.
 
=={{header|ProtiumProlog}}==
Works with SWI-Prolog.
Literate mode
<syntaxhighlight lang="prolog">rosetta_sleep(Time) :-
<lang html><@ SAYLIT>Number of seconds: </@><@ GETVAR>secs</@>
<@ SAYLIT> writeln('Sleeping</@>...'),
sleep(Time),
<@ ACTPAUVAR>secs</@>
writeln('Awake!').
<@ SAYLIT>Awake</@></lang>
</syntaxhighlight>
 
French variable-length opcodes
<lang html><# MontrezLittéralement>Number of seconds: </#><# PrenezUneValeurVariable>secs</#>
<# MontrezLittéralement>Sleeping</#>
<# AgissezFaireUnePauseVariable>secs</#>
<# MontrezLittéralement>Awake</#></lang>
 
(Simplified) Chinese fixed-length opcodes
<lang html><@ 显示_字串_>Number of seconds: </@><@ 获取_变量_>secs</@>
<@ 显示_字串_>Sleeping</@>
<@ 运行_暂停动变量_>secs</@>
<@ 显示_字串_>Awake</@></lang>
 
=={{header|PureBasic}}==
Sleeping is performed with Delay() and a value in milliseconds. The time is accurate to approximately +/- 15 milliseconds.
<langsyntaxhighlight PureBasiclang="purebasic">If OpenConsole()
 
Print("Enter a time(milliseconds) to sleep: ")
Line 577 ⟶ 2,117:
Input()
CloseConsole()
EndIf</langsyntaxhighlight>
 
=={{header|Python}}==
 
<langsyntaxhighlight lang="python">import time
 
seconds = float(raw_input())
print "Sleeping..."
time.sleep(seconds) # number is in seconds ... but accepts fractions
print "Awake!"</langsyntaxhighlight>
 
=={{header|R}}==
The call to flush.console is only needed if buffering is turned on. See [http://cran.r-project.org/bin/windows/base/rw-FAQ.html#The-output-to-the-console-seems-to-be-delayed FAQ for R on windows]. The time is given in seconds (fractions allowed, resolution is system dependent).
<syntaxhighlight lang="r">
<lang R>
sleep <- function(time=1)
{
Line 600 ⟶ 2,140:
 
sleep()
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">
#lang racket
(displayln "Enter a time (in seconds): ")
(define time (read))
(when (number? time)
(displayln "Sleeping...")
(sleep time)
(displayln "Awake!"))
</syntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
 
The <tt>sleep</tt> function argument is in units of seconds, but these may be fractional (to the limits of your system's clock).
 
<syntaxhighlight lang="raku" line>my $sec = prompt("Sleep for how many microfortnights? ") * 1.2096;
say "Sleeping...";
sleep $sec;
say "Awake!";</syntaxhighlight>
 
Note that 1.2096 is a rational number in Raku, not floating point, so precision can be maintained even when dealing with very small powers of ten.
 
=={{header|RapidQ}}==
<syntaxhighlight lang="vb">
input "Enter the number of seconds to sleep: ";s
sleep s
print "I'm awake I think..."
input "Press enter to quit";a$
</syntaxhighlight>
 
=={{header|REBOL}}==
<langsyntaxhighlight REBOLlang="rebol">REBOL [
Title: "Sleep Main Thread"
Date: 2009-12-15
Author: oofoe
URL: http://rosettacode.org/wiki/Sleep_the_Main_Thread
]
Line 613 ⟶ 2,182:
print "Sleeping..."
wait naptime
print "Awake!"</langsyntaxhighlight>
 
=={{header|Red}}==
<syntaxhighlight lang="red">
str-time: to integer! ask "Enter wait time " ;get user input , convert to integer
print "waiting"
wait str-time ;Seconds
print "awake"</syntaxhighlight>
 
=={{header|Retro}}==
Retro has no fine grained timer; so we have to make due with seconds.
 
<langsyntaxhighlight Retrolang="retro">: sleep ( n- )
[ time [ time over - 1 > ] until drop ] times ;
: test
"\nTime to sleep (in seconds): " puts getToken toNumber
"\nSleeping..." sleep
"\nAwake!\n" ;</langsyntaxhighlight>
 
=={{header|REXX}}==
===using the DELAY BIF===
Not all REXX interpretors have the DELAY built-in function.
This REXX version supplied &nbsp; ''as is'' &nbsp; works with &nbsp; (without the accompanying external program shown below):
<lang rexx>
:::* PC/REXX
/*REXX program to sleep x seconds (base in the argument). */
:::* Personal REXX
 
Note: &nbsp; the above two REXX interpreters support fractional seconds.
parse arg secs . /*get a (possible) argument. */
<syntaxhighlight lang="rexx">/*REXX program sleeps X seconds (the number of seconds is supplied via the argument).*/
secs=word(secs 0,1) /*if not present, assume 0 (zero)*/
sayparse 'Sleeping'arg secs "seconds." /*tell 'em what's happening. /*obtain optional argument from the CL.*/
callif delay(secs) =='' | secs=="," then secs=0 /*snooze.Not specified? Hopefully, aThen shortassume nap0 (zero).*/
say 'Awake!Sleeping' secs "seconds." /*andinform tellthe 'eminvoker wewhat'res runninghappening. */
call delay secs /*Snooze. Hopefully, just a short nap.*/
</lang>
say 'Awake!' /*and now inform invoker we're running.*/
Output after the following was used for input:
/*stick a fork in it, we're all done. */</syntaxhighlight>
<br><br>
'''output''' &nbsp; when using the following for input: &nbsp; <tt> 4.7 </tt>
4.7
<pre>
<pre style="height:10ex;overflow:scroll">
Sleeping 4.7 seconds.
Awake!
</pre>
 
===using the DELAY routine===
The above REXX program (using DELAY) will work with most REXXes:
:::* &nbsp; CMS REXX
:::* &nbsp; PC/REXX &nbsp; (see note)
:::* &nbsp; Personal REXX &nbsp; (see note)
:::* &nbsp; REGINA REXX
:::* &nbsp; ROO REXX
:::* &nbsp; R4 REXX
:::* &nbsp; TSO REXX
:::* &nbsp; (Microsoft) DOS
:::* &nbsp; (Microsoft) Windows
:::* &nbsp; any system that supports the &nbsp; PING &nbsp; command
when used in conjunction with the following program (either external or imbedded).
 
<br>Note: &nbsp; when PC/REXX or Personal REXX are used, those REXXes already have a built-in function (BIF), so the &nbsp; '''delay''' &nbsp; subroutine (below) will never be executed, but for other REXXes, the &nbsp; '''DELAY''' &nbsp; BIF will be used instead.
 
This REXX program only uses whole seconds &nbsp; (fractional seconds are ignored).
<syntaxhighlight lang="rexx">/*REXX program delays (or SLEEPS) a number of whole seconds; fractional secs are ignored*/
trace off /*suppress REXX error messages. */
parse arg ! /*obtain all the arguments. */
if !all(arg()) then exit /*documentation requested ? */
if !cms then address '' /*if CMS, then use fast cmd path.*/
signal on halt /*handle HALT gracefully. */
signal on noValue /*handle the REXX noValue error. */
signal on syntax /*handle the REXX syntax errors. */
 
/*┌────────────────────────────────────────────────────────────────────┐
┌─┘ The DELAY function is used to delay (wait) a specific amount of └─┐
│ (wall-clock) time specified in seconds. Any fraction part is ignored.│
│ │
│ If the REXX program invoking DELAY function is running under PC/REXX │
│ or Personal REXX, this REXX program should never be invoked as those │
└─┐ REXXes have their own built-in function (BIF) named "DELAY". ┌─┘
└────────────────────────────────────────────────────────────────────┘*/
 
@cpsleep = 'CP SLEEP' /*point to the (CP) SLEEP command*/
@ping = 'PING' /* " " " DOS PING " */
 
parse var ! n _ /*parse argument from the parms. */
if _\=='' | arg()>1 then call er 59 /*are there too many arguments ? */
if n=='' then n=1 /*No args? Then assume 1 second*/
if \isNum(n) then call er 53,n 'delay-seconds' /*is n not numeric? Error. */
n=n%1 /*elide any fractional second. */
if n<=0 then return 0
/* ┌────────────────────┐ */
/* │ delay n seconds. │ */
/* └────────────────────┘ */
select
when !cms then @cpsleep n%1 "SEC" /*is this CMS? Then use CP SLEEP*/
when !tso then call sleep n%1 /* " " TSO? " " SLEEP */
when !regina then call sleep n%1 /* " " Regina? " " " */
when !dos then @ping '-n' n "127.0.0.1 > NUL" /* " " DOS? " " PING */
otherwise nop
end /*select*/
 
return 0 /*return a zero value to invoker.*/
/*─────────────────────────────general 1─line subroutines───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────*/
!all: !!=!;!=space(!);upper !;call !fid;!nt=right(!var('OS'),2)=="NT";!cls=word('CLS VMFCLEAR CLRSCREEN',1+!cms+!tso*2);if arg(1)\==1 then return 0;if wordpos(!,"? ?SAMPLES ?AUTHOR ?FLOW")==0 then return 0;!call=']$H';call "$H" !fn !;!call=;return 1
!cal: if symbol('!CALL')\=="VAR" then !call=; return !call
!env: !env='ENVIRONMENT'; if !sys=="MSDOS" | !brexx | !r4 | !roo then !env='SYSTEM'; if !os2 then !env="OS2"!env; !ebcdic=3=='f3'x; if !crx then !env="DOS"; return
!fid: parse upper source !sys !fun !fid . 1 . . !fn !ft !fm .; call !sys; if !dos then do; _=lastpos('\',!fn); !fm=left(!fn,_); !fn=substr(!fn,_+1); parse var !fn !fn "." !ft; end; return word(0 !fn !ft !fm, 1+('0'arg(1)))
!rex: parse upper version !ver !vernum !verdate .; !brexx='BY'==!vernum; !kexx="KEXX"==!ver; !pcrexx='REXX/PERSONAL'==!ver | "REXX/PC"==!ver; !r4='REXX-R4'==!ver; !regina="REXX-REGINA"==left(!ver,11); !roo='REXX-ROO'==!ver; call !env; return
!sys: !cms=!sys=='CMS'; !os2=!sys=="OS2"; !tso=!sys=='TSO' | !sys=="MVS"; !vse=!sys=='VSE'; !dos=pos("DOS",!sys)\==0 | pos('WIN',!sys)\==0 | !sys=="CMD"; !crx=left(!sys,6)=='DOSCRX'; call !rex; return
!var: call !fid; if !kexx then return space(dosenv(arg(1))); return space(value(arg(1), , !env))
er: parse arg _1,_2; call '$ERR' "14"p(_1) p(word(_1,2) !fid(1)) _2; if _1<0 then return _1; exit result
p: return word(arg(1), 1)
halt: call er .1
isNum: return datatype(arg(1), 'N')
noValue: !sigl=sigl; call er 17, !fid(2) !fid(3) !sigl condition('D') sourceline(!sigl)
syntax: !sigl=sigl; call er 13, !fid(2) !fid(3) !sigl !cal() condition('D') sourceline(!sigl)</syntaxhighlight>
Coding note: &nbsp; the &nbsp; '''!''' &nbsp; subroutines (above) deal mostly with determining what version of REXX is being invoked and what operating system is being used; &nbsp; and based on that information, appropriate flags (variables) are set. &nbsp; This is an example of a robust boilerplate code checking for various versions of REXX and operating systems, and it also defines additional flags not used within this particular program.
 
Programming note: &nbsp; The subroutine &nbsp; '''$ERR''' &nbsp; isn't included here; so here is the gist of the error messages:
::* &nbsp; er 59 &nbsp; &nbsp; &nbsp; too many arguments specified for the ─── DELAY ─── command.
::* &nbsp; er 53 &nbsp; &nbsp; &nbsp; argument ─── xxx ─── isn't numeric for the option ─── delay-seconds ─── for the ─── DELAY ─── command.
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
load "guilib.ring"
 
for n = 1 to 10
Sleep(3)
see "" + n + " "
next
see nl
 
func Sleep x
nTime = x * 1000
oTest = new qTest
oTest.qsleep(nTime)
</syntaxhighlight>
 
Output:
 
<pre>
1 2 3 4 5 6 7 8 9 10
</pre>
 
=={{header|RPL}}==
{| class="wikitable"
! RPL code
! Comment
|-
|
CLLD "Sleeping..." 1 DISP
WAIT
CLMF "Awake!"
≫ ‘'''SLEEP'''’ STO
|
'''SLEEP''' ''( seconds -- "Awake!" )''
clear screen and display message on top of screen
sleep the given number of seconds
reactivate the stack display
|}
{{in}}
<pre>
10 SLEEP
</pre>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">seconds = gets.to_f
puts "Sleeping..."
sleep(seconds) # number is in seconds ... but accepts fractions
# Minimum resolution is system dependent.
puts "Awake!"</langsyntaxhighlight>
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">use std::{io, time, thread};
 
fn main() {
println!("How long should we sleep in milliseconds?");
let mut sleep_string = String::new();
 
io::stdin().read_line(&mut sleep_string)
.expect("Failed to read line");
 
let sleep_timer: u64 = sleep_string.trim()
.parse()
.expect("Not an integer");
let sleep_duration = time::Duration::from_millis(sleep_timer);
println!("Sleeping...");
thread::sleep(sleep_duration);
println!("Awake!");
}</syntaxhighlight>
 
=={{header|Scala}}==
{{libheader|Scala}}<syntaxhighlight lang="scala">object Sleeper extends App {
print("Enter sleep time in milli sec: ")
val ms = scala.io.StdIn.readInt()
println("Sleeping...")
val sleepStarted = scala.compat.Platform.currentTime
Thread.sleep(ms)
println(s"Awaked after [${scala.compat.Platform.currentTime - sleepStarted} ms]1")
}</syntaxhighlight>
 
=={{header|Scheme}}==
 
Many Scheme implementations support srfi-18, a multithreading library which provides a 'thread-sleep!' function.
The following works in Chicken Scheme:
 
<syntaxhighlight lang="scheme">
(use format)
(use srfi-18)
 
(format #t "Enter a time (in seconds): ")
(let ((time (read))) ; converts input to a number, if possible
(if (number? time)
(begin
(format #t "Sleeping...~&")
(thread-sleep! time)
(format #t "Awake!~&"))
(format #t "You must enter a number~&")))
</syntaxhighlight>
 
Scheme implementations also provide alternative approaches. For example, Chicken Scheme has a 'posix' library which includes a 'sleep' function.
 
=={{header|Seed7}}==
 
The [http://seed7.sourceforge.net/libraries/duration.htm duration.s7i] library defines the function ''wait'', which takes an argument of type ''duration''. Functions to create durations with years, months, days, hours, minutes, seconds and micro seconds exist also.
 
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "duration.s7i";
 
const proc: main is func
local
var integer: secondsToSleep is 0;
begin
write("Enter number of seconds to sleep: ");
readln(secondsToSleep);
writeln("Sleeping...");
wait(secondsToSleep . SECONDS);
writeln("Awake!");
end func;</syntaxhighlight>
 
=={{header|SenseTalk}}==
SenseTalk understands time durations expressed in any units, including: seconds, minutes, days, microseconds, shakes, and jiffies!
<syntaxhighlight lang="sensetalk">
ask "How long would you like to sleep?" message "Your answer may include any duration, such as 5 seconds, 2 hours, or even 3 centuries!"
get the value of it
 
if it is a duration then
put it into sleepyTime
else
answer "Sorry, that wasn't a valid duration!"
exit all
end if
 
put "Sleeping for " & sleepyTime & "..."
wait sleepyTime
put "Awake!"
 
</syntaxhighlight>
 
=={{header|Sidef}}==
<syntaxhighlight lang="ruby">var sec = read(Number); # any positive number (it may be fractional)
say "Sleeping...";
Sys.sleep(sec); # in seconds
#Sys.usleep(sec); # in microseconds
#Sys.nanosleep(sec); # in nanoseconds
say "Awake!";</syntaxhighlight>
 
=={{header|Smalltalk}}==
{{works with|Pharo}}
<syntaxhighlight lang="smalltalk">t := (FillInTheBlankMorph request: 'Enter time in seconds') asNumber.
Transcript show: 'Sleeping...'.
(Delay forSeconds: t) wait.
Transcript show: 'Awake!'.
</syntaxhighlight>
{{works with|Smalltalk/X}}
<syntaxhighlight lang="smalltalk">t := (Dialog request: 'Enter time in seconds') asNumber.
Transcript show: 'Sleeping...'.
(Delay forSeconds: t) wait.
Transcript show: 'Awake!'.
</syntaxhighlight>
(of course, you can "Smalltalk at:#FillInTheBlankMorph put:Dialog", to be source compatible with Pharo)
 
=={{header|SparForte}}==
As a structured script.
<syntaxhighlight lang="ada">#!/usr/local/bin/spar
pragma annotate( summary, "sleep_demo" );
pragma annotate( description, "Write a program that does the following in this order:" );
pragma annotate( description, "" );
pragma annotate( description, "* Input an amount of time to sleep in whatever units are" );
pragma annotate( description, "most natural for your language (milliseconds, seconds," );
pragma annotate( description, "ticks, etc.). This unit should be noted in comments or" );
pragma annotate( description, "in a description." );
pragma annotate( description, "* Print 'Sleeping...'" );
pragma annotate( description, "* Sleep the main thread for the given amount of time." );
pragma annotate( description, "* Print 'Awake!'" );
pragma annotate( description, "* End." );
pragma annotate( see_also, "http://rosettacode.org/wiki/Sleep" );
pragma annotate( author, "Ken O. Burtch" );
pragma license( unrestricted );
 
procedure sleep_demo is
in_val : duration;
begin
? "Number of seconds to sleep?";
in_val := numerics.value( get_line );
 
-- Using delay
? "Sleeping...";
delay in_val;
? "Awake!";
 
-- Using Linux/UNIX sleep
? "Sleeping...";
sleep "$in_val" ;
? "Awake!";
end sleep_demo;</syntaxhighlight>
 
=={{header|Standard ML}}==
<langsyntaxhighlight lang="ocaml">(TextIO.print "input a number of seconds please: ";
let val seconds = valOf (Int.fromString (valOf (TextIO.inputLine TextIO.stdIn))) in
TextIO.print "Sleeping...\n";
Line 659 ⟶ 2,504:
I dunno why; it doesn't say anything about this in the documentation *)
TextIO.print "Awake!\n"
end)</langsyntaxhighlight>
 
=={{header|Stata}}==
<syntaxhighlight lang="stata">program sleep_awake
* pass duration in milliseconds
display "Sleeping..."
sleep `0'
display "Awake!"
end
 
sleep_awake 2000</syntaxhighlight>
 
=={{header|Suneido}}==
<langsyntaxhighlight Suneidolang="suneido">function (time)
{
Print("Sleeping...")
Sleep(time) // time is in milliseconds
Print("Awake!")
}</langsyntaxhighlight>
 
=={{header|Swift}}==
<syntaxhighlight lang="swift">import Foundation
 
println("Enter number of seconds to sleep")
let input = NSFileHandle.fileHandleWithStandardInput()
var amount = NSString(data:input.availableData, encoding: NSUTF8StringEncoding)?.intValue
var interval = NSTimeInterval(amount!)
println("Sleeping...")
NSThread.sleepForTimeInterval(interval)
 
println("Awake!")</syntaxhighlight>
 
=={{header|Tcl}}==
Blocking example (the process is blocked preventing any background activity).
<langsyntaxhighlight lang="tcl">puts -nonewline "Enter a number of milliseconds to sleep: "
flush stdout
set millis [gets stdin]
puts Sleeping...
after $millis
puts Awake!</langsyntaxhighlight>
 
A non-blocking example where background activity will occur.
<langsyntaxhighlight lang="tcl">puts -nonewline "Enter a number of milliseconds to sleep: "
flush stdout
set millis [gets stdin]
Line 686 ⟶ 2,553:
after $millis set ::wakeupflag 1
vwait ::wakeupflag
puts Awake!</langsyntaxhighlight>
 
=={{header|TI-89 BASIC}}==
Line 715 ⟶ 2,582:
 
45 sleep</pre>
 
=={{header|TUSCRIPT}}==
<syntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
secondsrange=2
PRINT "Sleeping ",secondsrange," seconds "
WAIT #secondsrange
PRINT "Awake after Naping ",secondsrange, " seconds"
</syntaxhighlight>
 
=={{header|TXR}}==
 
<syntaxhighlight lang="txrlisp">(let ((usec (progn (put-string "enter sleep usecs: ")
(tointz (get-line)))))
(put-string "Sleeping ... ")
(flush-stream)
(usleep usec)
(put-line "Awake!"))</syntaxhighlight>
 
=={{header|UNIX Shell}}==
<syntaxhighlight lang="bash">printf "Enter a time in seconds to sleep: "
{{works with|Bash}}
read seconds
<lang bash>read -p "Enter a time in seconds to sleep: " seconds
echo "Sleeping..."
sleep "$seconds"
echo "Awake!"</langsyntaxhighlight>
 
This uses the [http://www.openbsd.org/cgi-bin/man.cgi?query=sleep&apropos=0&sektion=1&manpath=OpenBSD+Current&arch=i386&format=html sleep(1)] command. POSIX sleep(1) only takes an integer, as in <tt>sleep 2</tt>, so you can only sleep for a whole number of seconds. Some systems extend sleep(1) to take a decimal fraction, as in <tt>sleep 2.5</tt>.
 
=={{header|Ursa}}==
<syntaxhighlight lang="ursa">out "Sleeping..." endl console
# sleep for 5 seconds (5000 milliseconds)
sleep 5000
out "Awake!" endl console</syntaxhighlight>
 
=={{header|VBA}}==
<syntaxhighlight lang="vba">
Function Sleep(iSecsWait As Integer)
Debug.Print Now(), "Sleeping..."
Application.Wait Now + iSecsWait / 86400 'Time is stored as fractions of 24 hour day
Debug.Print Now(), "Awake!"
End Function
</syntaxhighlight>
 
=={{header|VBScript}}==
<syntaxhighlight lang="vbscript">
iSeconds=InputBox("Enter a time in seconds to sleep: ","Sleep Example for RosettaCode.org")
WScript.Echo "Sleeping..."
WScript.Sleep iSeconds*1000 'Sleep is done in Milli-Seconds
WScript.Echo "Awake!"
</syntaxhighlight>
 
<!--Out of alphabetical order to keep the VB languages together-->
 
=={{header|Vedit macro language}}==
<langsyntaxhighlight lang="vedit">#1 = Get_Num("Sleep time in 1/10 seconds: ")
Message("Sleeping...\n")
Sleep(#1)
Message("Awake!\n")</langsyntaxhighlight>
 
=={{header|Visual Basic .NET}}==
 
<syntaxhighlight lang="vbnet">Module Program
Sub Main()
Dim millisecondsSleepTime = Integer.Parse(Console.ReadLine(), Globalization.CultureInfo.CurrentCulture)
Console.WriteLine("Sleeping...")
Threading.Thread.Sleep(millisecondsSleepTime)
Console.WriteLine("Awake!")
End Sub
End Module</syntaxhighlight>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">import time
import os
 
fn main() {
sec := os.input("Enter number of seconds to sleep: ").i64()
println("Sleeping…")
time.sleep(time.Duration(sec * time.second))
println("Awake!")
}</syntaxhighlight>
 
=={{header|Wren}}==
<syntaxhighlight lang="wren">import "timer" for Timer
import "io" for Stdin, Stdout
 
System.write("Enter time to sleep in seconds: ")
Stdout.flush()
var secs
while (true) {
secs = Num.fromString(Stdin.readLine())
if (secs == null) {
System.print("Not a number try again.")
} else break
}
System.print("Sleeping...")
Timer.sleep((secs*1000).floor)
System.print("Awake!")</syntaxhighlight>
 
{{out}}
Sample session:
<pre>
Enter time to sleep in seconds: 10
Sleeping...
Awake!
</pre>
 
=={{header|X86 Assembly}}==
==={{header|NASM 2.15}}===
<syntaxhighlight lang="asm">
%macro sysdef 2
%define sys_%1 %2
%endmacro
sysdef write, 1
sysdef exit, 60
sysdef nanosleep, 35
 
%macro inv 1-7 0,0,0,0,0,0
mov r9,%7
mov r8,%6
mov r10,%5
mov rdx,%4
mov rsi,%3
mov rdi,%2
mov rax,sys_%1
syscall
%endmacro
 
section .data
timeval:
tv_sec dq 0
tv_nsec dq 0
 
section .rodata
str1 db "Sleeping",0xa,0
str2 db "Awake!",0xa,0
 
section .text
 
global main
main:
lea rbx, [rel str1]
inv write, 1, rbx, 9
mov qword [rel tv_sec], 5
mov qword [rel tv_nsec], 0
lea rax, [rel timeval]
inv nanosleep, rax, 0
lea rbx, [rel str2]
inv write, 1, rbx, 7
lea rbx, [rel str2]
inv exit, 0
ret
</syntaxhighlight>
 
 
This sleep subroutine takes the number of seconds to sleep as a parameter.
The actual linux syscall that I use to implement this takes a time struct (seconds at the first qword and nanoseconds at the second) as the first argument. Optionally you can pass another time stuct as a second argument. In the event that the sleep is interrupted by a system event, linux will fill this second struct with the remaining time so the syscall can be called again with the remaining sleep time.
 
<syntaxhighlight lang="x86asm">
; x86_64 linux nasm
 
section .text
 
Sleep:
mov rsi, 0 ; we wont use the second sleep arg, pass null to syscall
sub rsp, 16
mov qword [rsp], rdi ; number of seconds the caller requested
mov qword [rsp + 8], rsi ; we won't use the nanoseconds
mov rdi, rsp ; pass the struct that's on the stack to
mov rax, 35 ; sys_nanosleep
syscall
add rsp, 16 ; clean up stack
ret
</syntaxhighlight>
 
=={{header|XPL0}}==
<syntaxhighlight lang="xpl0">int Microseconds;
[Microseconds:= IntIn(0);
Text(0, "Sleeping...^m^j");
DelayUS(Microseconds);
Text(0, "Awake!^m^j");
]</syntaxhighlight>
 
=={{header|zig}}==
<syntaxhighlight lang="zig">const std = @import("std");
const time = std.time;
const warn = std.debug.warn;
 
pub fn main() void {
warn("Sleeping...\n");
 
time.sleep(1000000000); // `sleep` uses nanoseconds
 
warn("Awake!\n");
}</syntaxhighlight>
 
=={{header|zkl}}==
<syntaxhighlight lang="zkl">seconds:=ask("Seconds to sleep: ").toFloat();
println("Sleeping...");
Atomic.sleep(seconds); # float, usually millisecond resolution
println("Awake!");</syntaxhighlight>
 
=={{header|Zoomscript}}==
For typing:
<syntaxhighlight lang="zoomscript">print "Sleeping..."
wait 1
println
print "Awake!"</syntaxhighlight>
For importing:
 
¶0¶print "Sleeping..."¶0¶wait 1¶0¶println¶0¶print "Awake!"
 
{{Omit From|Metafont}}
{{omit from|M4}}
{{omit from|ML/I}}
{{Omit From|Metafont}}
{{omit from|PostScript}}
9,476

edits