Sleep: Difference between revisions
m
→{{header|Wren}}: Changed to Wren S/H
Thundergnat (talk | contribs) m (→{{header|Raku}}: Fix-up some Perl6 -> Raku references) |
m (→{{header|Wren}}: Changed to Wren S/H) |
||
(46 intermediate revisions by 31 users not shown) | |||
Line 13:
* [[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
Line 124 ⟶ 132:
* --------------------------------------------------------------------
END SLEEP
</syntaxhighlight>
'''output''' invoked with PARM='6' (+ sign indicates "problem state" (non system key) execution
<pre style="overflow:scroll">
Line 133 ⟶ 141:
=={{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.
<
jmp main
ORG TIMER0
Line 155 ⟶ 163:
; Awake!
jmp $</
=={{header|8th}}==
<
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 169 ⟶ 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.
<
with Ada.Float_Text_Io; use Ada.Float_Text_Io;
Line 179 ⟶ 391:
delay Duration(In_Val);
Put_Line("Awake!");
end Sleep;</
=={{header|Aime}}==
<
# Sleep X seconds
Line 190 ⟶ 402:
#usleep(atoi(argv(1)));
o_text("Awake!\n");</
=={{header|ALGOL 68}}==
Line 196 ⟶ 408:
{{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.
<
INT milliseconds = read int; # ping uses milliseconds #
print ("Sleeping...");
Line 203 ⟶ 415:
# ping -n gives number of tries, -w timeout, and >NUL deletes output so the user does not see it #
print (new line);
print ("Awake!")</
=={{header|AntLang}}==
<
echo["Sleeping..."]
sleep[milliseconds]
echo["Awake!"]</
=={{header|Applesoft BASIC}}==
The cycles and times calculated should only be taken as a minimum delay.
<
20 POKE 771,168: POKE 772,252
30 INPUT "ENTER WAIT VALUE (1-256) : ";A
Line 221 ⟶ 433:
70 PRINT "WAIT FOR "C" CYCLES OR "
80 PRINT C * 14 / 14.318181" MICROSECONDS"
90 PRINT "SLEEPING": CALL 768: PRINT "AWAKE"</
Output:<pre>ENTER WAIT VALUE (1-256) : 256
WAIT FOR 167309 CYCLES OR
Line 231 ⟶ 443:
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
Line 397 ⟶ 609:
.align 4
</syntaxhighlight>
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">time: to :integer input "Enter number of milliseconds: "
print "Sleeping..."
pause time
print "Awake!"</
{{out}}
<pre>Enter
Sleeping...
Awake!</pre>
=={{header|AutoHotkey}}==
<
sleep, 2000 ; 2 seconds
TrayTip, awake, awake
Msgbox, awake</
=={{header|AutoIt}}==
<
$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")</
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f SLEEP.AWK [seconds]
BEGIN {
Line 442 ⟶ 651:
while (systime() < t + seconds) {}
}
</syntaxhighlight>
<p>commands and output:</p>
<pre>
Line 458 ⟶ 667:
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.
<
input→A
0→T
Line 472 ⟶ 681:
Disp "SLEEPING...",i
Pause T
Disp "AWAKE",i</
=={{header|BASIC}}==
{{works with|QuickBasic|4.5}}
<
PRINT "Sleeping..."
SLEEP sec
PRINT "Awake!"</
"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|BASIC256}}===
<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}}===
Line 501 ⟶ 738:
(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>)
<
20 PRINT "(IN TELEVISION FRAMES)"
30 INPUT SLEEPTIME
40 PRINT "SLEEPING... ";
50 PAUSE SLEEPTIME
60 PRINT "AWAKE."</
===
<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.
<
20 LET s = 5
30 PRINT "Sleeping"
40 PAUSE s * 50
50 PRINT "Awake"</
=={{header|Batch File}}==
Line 522 ⟶ 770:
{{works with|Windows NT|4}}
<
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!</
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}}
<
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!</
Starting with Windows Vista there is a command-line utility to wait a number of seconds:
{{works with|Windows Vista}}
<
set /p Seconds=Enter the number of seconds to sleep:
echo Sleeping ...
timeout /t %Seconds% /nobreak >nul
echo Awake!</
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<
PRINT "Sleeping..."
WAIT sleep%
PRINT "Awake!"</
Whilst sleeping BBC BASIC for Windows periodically tests for the ESCape key being pressed.
Line 560 ⟶ 808:
The function <tt>sleep</tt> needs seconds, which are read from the standard input.
<
#include <unistd.h>
Line 571 ⟶ 819:
printf("Awake!\n");
return 0;
}</
=={{header|C sharp|C#}}==
<
using System.Threading;
Line 587 ⟶ 835:
Console.WriteLine("Awake!");
}
}</
=={{header|C++}}==
Line 593 ⟶ 841:
{{works with|C++11}}
<
#include <thread>
#include <chrono>
Line 604 ⟶ 852:
std::cout << "Awake!\n";
}
</syntaxhighlight>
{{works with|POSIX}}
<
#include <iostream>
Line 621 ⟶ 869:
cout << "Awake!" << endl;
return 0;
}</
=={{header|Caché ObjectScript}}==
<syntaxhighlight lang="caché objectscript">
SLEEP
; the HANG command can use fractional seconds; the Awake line will be slightly off due to processing time
Line 632 ⟶ 880:
write !,"Awake! Time is "_$ztime($piece($ztimestamp,",",2,2),1,2)
quit
</syntaxhighlight>
{{out}}<pre>
Line 642 ⟶ 890:
=={{header|Clojure}}==
<
(println "Sleeping...")
(Thread/sleep ms)
(println "Awake!"))
; call it
(sleep 1000)</
=={{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|
<
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|
<
PROGRAM-ID. Sleep-In-Nanoseconds.
OPTIONS.
DEFAULT ROUNDED MODE IS NEAREST-AWAY-FROM-ZERO.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Seconds-To-Sleep USAGE
01 Nanoseconds-To-Sleep USAGE
01 Nanoseconds-Per-Second CONSTANT AS 1000000000.
PROCEDURE DIVISION.
ACCEPT Seconds-To-Sleep
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}}==
<
(let ((seconds (read)))
(format t "Sleeping...~%")
Line 706 ⟶ 976:
(format t "Awake!~%")))
(test-sleep)</
=={{header|D}}==
<
void main() {
Line 720 ⟶ 990:
Thread.sleep(dur!"seconds"(secs));
writeln("Awake!");
}</
{{out}}
<pre>Enter a time to sleep (in seconds): 5
Line 727 ⟶ 997:
=={{header|DCL}}==
<
$ write sys$output "Sleeping..."
$ wait 'amount_of_time
$ write sys$output "Awake!"</
{{out}}
<pre>$ @sleep 1 ! sleeps for 1 hour
Line 747 ⟶ 1,017:
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}}==
<
{$APPTYPE CONSOLE}
Line 765 ⟶ 1,049:
Sleep(lTimeToSleep); // milliseconds
WriteLn('Awake!');
end.</
=={{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
Line 789 ⟶ 1,087:
</syntaxhighlight>
=={{header|E}}==
Line 798 ⟶ 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.
<
stdout.println("Sleeping...")
timer.whenPast(timer.now() + milliseconds, fn {
Line 804 ⟶ 1,102:
nextThing()
})
}</
=={{header|EasyLang}}==
<syntaxhighlight lang="easylang">
print "How many seconds should I sleep? "
sec = number input
print "Sleeping ..."
sleep sec
print "Awake!"
</syntaxhighlight>
=={{header|EGL}}==
<
// Syntax: sysLib.wait(time BIN(9,2) in)
Line 817 ⟶ 1,124:
end
end</
=={{header|Eiffel}}==
Line 825 ⟶ 1,132:
<code lang="eiffel">sleep</code> takes an argument which declares the number of nanoseconds to suspend the thread's execution.
<
APPLICATION
inherit
Line 841 ⟶ 1,148:
print ("Awake!%N")
end
end</
Output (sleeping 10 seconds):
Line 852 ⟶ 1,159:
=={{header|Elena}}==
ELENA 4.x :
<
public program()
Line 860 ⟶ 1,167:
system'threading'threadControl.sleep(sleep);
console.printLine("Awake!")
}</
=={{header|Elixir}}==
<
IO.puts "Sleeping..."
:timer.sleep(1000 * seconds) # in milliseconds
Line 870 ⟶ 1,177:
sec = if System.argv==[], do: 1, else: hd(System.argv) |> String.to_integer
sleep.(sec)</
=={{header|Emacs Lisp}}==
(message "Sleeping ...")
(sleep-for seconds)
(message "Awake!"))</
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!
</pre>
=={{header|Erlang}}==
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:
<
io:format("Sleeping...~n"),
timer:sleep(1000), %% in milliseconds
io:format("Awake!~n").</
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:
<
io:format("Sleeping...~n"),
receive
after 1000 -> ok %% in milliseconds
end,
io:format("Awake!~n").</
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)
Line 912 ⟶ 1,237:
PRINT("Awake!")
..............
</syntaxhighlight>
=={{header|F_Sharp|F#}}==
{{trans|C#}}
<
open System.Threading
Line 925 ⟶ 1,250:
Thread.Sleep(sleep); //milliseconds
Console.WriteLine("Awake!")
0</
=={{header|Factor}}==
<
: read-sleep ( -- )
Line 934 ⟶ 1,259:
"Sleeping..." print
sleep
"Awake!" print ;</
=={{header|Fantom}}==
Line 940 ⟶ 1,265:
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.
<
using concurrent
Line 962 ⟶ 1,287:
}
}
</syntaxhighlight>
Output:
Line 973 ⟶ 1,298:
=={{header|FBSL}}==
<
DIM %msec
PRINT "Milliseconds to sleep: ";
Line 981 ⟶ 1,306:
PRINT "Awake!"
PAUSE
</syntaxhighlight>
Output
<pre>Milliseconds to sleep: 1000
Line 990 ⟶ 1,315:
=={{header|Forth}}==
<
." Sleeping..."
ms
." awake." cr ;</
====Explanation note on MS====
Line 1,002 ⟶ 1,327:
=={{header|Fortran}}==
<
implicit none
Line 1,019 ⟶ 1,344:
end if
end program test_sleep</
=={{header|FreeBASIC}}==
<
Dim ms As UInteger
Line 1,029 ⟶ 1,354:
Sleep ms, 1 '' the "1" means Sleep can't be interrupted with a keystroke
Print "Awake!"
End</
Sample input/output
Line 1,041 ⟶ 1,366:
=={{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.
<
do
t = eval[input["Enter amount of time to sleep: ", "1 second"]]
Line 1,049 ⟶ 1,374:
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.
<
import "time"
Line 1,065 ⟶ 1,390:
time.Sleep(time.Duration(sec * float64(time.Second)))
fmt.Println("\nAwake!")
}</
=={{header|Groovy}}==
Solution:
<
println("Sleeping...")
sleep(it)
println("Awake!")
}</
Test:
<
print '''
Hmmm. That was... less than satisfying.
Line 1,087 ⟶ 1,412:
}
}
sleepTest(5000)</
Output:
Line 1,105 ⟶ 1,430:
=={{header|Haskell}}==
<
main = do seconds <- readLn
putStrLn "Sleeping..."
threadDelay $ round $ seconds * 1000000
putStrLn "Awake!"</
=={{header|HicEst}}==
<
WRITE(StatusBar) "Sleeping ... "
SYSTEM(WAIT = milliseconds)
WRITE(Messagebox) "Awake!"</
=={{header|Icon}} and {{header|Unicon}}==
<
repeat {
Line 1,130 ⟶ 1,455:
delay(1000 * s)
write("Awake!")
end</
=={{header|IDL}}==
<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''':
<
sleeping=: monad define
Line 1,150 ⟶ 1,475:
sleep y
smoutput 'Awake!'
)</
'''Example''':
<
Sleeping...
Awake!</
=={{header|Java}}==
{{works with|Java|1.5+}}
<
import java.util.InputMismatchException;
import java.util.Scanner;
Line 1,174 ⟶ 1,499:
}
}
}</
===Using Java 8===
<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.
<
setTimeout(function () {
Line 1,188 ⟶ 1,548:
document.write('Sleeping... ');
</script></
=={{header|jq}}==
`sleep($n)` will pause (busily) for at least the given time period, measured in seconds.
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">
# Pseudosleep for at least the given number of $seconds (a number)
# and emit the actual number of seconds that have elapsed.
def sleep($seconds):
now
| . as $now
| until( . - $now >= $seconds; now)
| . - $now ;
</syntaxhighlight>
=={{header|Jsish}}==
<
Sleep, in Jsish
*/
Line 1,200 ⟶ 1,574:
puts('Sleeping...');
sleep(ms);
puts('Awake!');</
=={{header|Julia}}==
<syntaxhighlight lang="julia">
print("Please enter sleep duration in seconds: ")
input = int(readline(STDIN))
Line 1,210 ⟶ 1,584:
sleep(input)
println("Awake!")
</syntaxhighlight>
=={{header|Kotlin}}==
<
fun main(args: Array<String>) {
Line 1,221 ⟶ 1,595:
Thread.sleep(ms)
println("Awake!")
}</
Sample input/output:
{{out}}
Line 1,234 ⟶ 1,608:
<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.
<
sleep(5000) // Sleep 5 seconds
stdoutnl('Awake!')</
=={{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
<
make "Long "U4
make "kernel32_handle libload "kernel32.dll
Line 1,255 ⟶ 1,637:
Sleep :n ; units: 1/1000th of a second
print [Awake.]
end</
=={{header|Liberty BASIC}}==
<
Print "Sleeping..."
CallDLL #kernel32, "Sleep", sleeptime As long, ret As void
Print "Awake!"
</syntaxhighlight>
=={{header|Lingo}}==
{{libheader|CommandLine Xtra}}
<
put "Sleeping..."
sleep(ms)
put "Awake!"
end</
=={{header|Logo}}==
<
to sleep :n
print [Sleeping...]
Line 1,279 ⟶ 1,661:
print [Awake.]
end
</syntaxhighlight>
=={{header|Logtalk}}==
Works when using SWI-Prolog, XSB, or YAP as the backend compilers:
<
:- object(sleep).
Line 1,294 ⟶ 1,676:
:- end_object.
</syntaxhighlight>
Sample output:
<
| ?- 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.
<
io.write("Input a number of seconds to sleep: ")
local input = io.read("*number")
print("Sleeping")
socket.sleep(input)
print("Awake!")</
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
Line 1,324 ⟶ 1,706:
}
CheckIt
</syntaxhighlight>
=={{header|Maple}}==
<
print("Sleeping...");
Threads:-Sleep(secs);
print("Awake!");
end proc:</
=={{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}}==
<
time = input('How many seconds would you like me to sleep for? ');
Line 1,350 ⟶ 1,729:
disp('Awake!');
end</
=={{header|min}}==
{{works with|min|0.19.6}}
<syntaxhighlight lang="min">"Enter number of milliseconds to sleep" ask int
"Sleeping..." puts!
sleep
"Awake!" puts!</syntaxhighlight>
=={{header|Nanoquery}}==
<
println "Sleeping..."
sleep(time)
println "Awake!"</
=={{header|Nemerle}}==
<
using System.Console;
using System.Threading.Thread; // this is where the Sleep() method comes from
Line 1,373 ⟶ 1,759:
WriteLine("Awake!");
}
}</
=={{header|NetRexx}}==
<
options replace format comments java crossref symbols nobinary
Line 1,413 ⟶ 1,799:
say
return
</syntaxhighlight>
=={{header|NewLISP}}==
<
(sleep 2000) ; Wait for 2 seconds
(println "Awake!")</
=={{header|Nim}}==
<
echo
var timed =
echo
sleep
echo
=={{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.
<
20 PAUSE 100
30 PRINT "NOW I'M AWAKE AGAIN."</
=={{header|Objeck}}==
<
bundle Default {
class Test {
Line 1,448 ⟶ 1,834:
}
}
</syntaxhighlight>
=={{header|Objective-C}}==
Line 1,455 ⟶ 1,841:
{{works with|GNUstep}} and {{works with|Cocoa}}
<
int main()
Line 1,471 ⟶ 1,857:
}
return 0;
}</
=={{header|OCaml}}==
<
let seconds = read_int ();;
print_endline "Sleeping...";;
Unix.sleep seconds;; (* number is integer in seconds *)
print_endline "Awake!";;</
or
<
#directory "+threads";;
#load "threads.cma";;
Line 1,488 ⟶ 1,874:
print_endline "Sleeping...";;
Thread.delay seconds;; (* number is in seconds ... but accepts fractions *)
print_endline "Awake!";;</
=={{header|Oforth}}==
<
=={{header|ooRexx}}==
<
Call sysSleep 10 -- wait 10 seconds
Say time()</
{{out}}
<pre>14:23:40
Line 1,502 ⟶ 1,888:
=={{header|Oz}}==
<
class TextFile from Open.file Open.text end
StdIn = {New TextFile init(name:stdin)}
Line 1,509 ⟶ 1,895:
{System.showInfo "Sleeping..."}
{Delay WaitTime} %% in milliseconds
{System.showInfo "Awake!"}</
=={{header|PARI/GP}}==
Line 1,516 ⟶ 1,902:
===gettime===
The units are milliseconds.
<
print("Sleeping...");
while((ms-=gettime()) > 0,);
Line 1,522 ⟶ 1,908:
};
sleep(input())</
===alarm===
{{works with|PARI/GP|2.4.3 and above on Linux}}
The units are seconds.
<
print("Sleeping...");
alarm(s);
Line 1,534 ⟶ 1,920:
};
sleep(input())</
=={{header|Pascal}}==
Line 1,541 ⟶ 1,927:
=={{header|Peloton}}==
Literate mode
<
<@ SAYLIT>Sleeping</@>
<@ ACTPAUVAR>secs</@>
<@ SAYLIT>Awake</@></
French variable-length opcodes
<
<# MontrezLittéralement>Sleeping</#>
<# AgissezFaireUnePauseVariable>secs</#>
<# MontrezLittéralement>Awake</#></
(Simplified) Chinese fixed-length opcodes
<
<@ 显示_字串_>Sleeping</@>
<@ 运行_暂停动变量_>secs</@>
<@ 显示_字串_>Awake</@></
=={{header|Perl}}==
seconds:
<
print "Sleeping...\n";
sleep $seconds; # number is in seconds
print "Awake!\n";</
microseconds and nanoseconds using the Time::HiRes module:
<
$microseconds = <>;
Line 1,577 ⟶ 1,963:
print "Sleeping...\n";
nanosleep $nanoseconds;
print "Awake!\n";</
It's also possible to sleep for fractional seconds by abusing the select function:
<
select undef, undef, undef, 0.5;
say "Awake!";</
=={{header|Phix}}==
{{libheader|Phix/basics}}
<!--<syntaxhighlight lang="phix">-->
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (prompt_number, sleep)</span>
<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>
<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>
<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>
<!--</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:
<
echo "Sleeping...\n";
sleep($seconds); # number is integer in seconds
echo "Awake!\n";</
microseconds:
<
echo "Sleeping...\n";
usleep($microseconds); # number is integer in microseconds
echo "Awake!\n";</
nanoseconds:
<
echo "Sleeping...\n";
time_nanosleep($seconds, $nanoseconds); # first arg in seconds plus second arg in nanoseconds
echo "Awake!\n";</
=={{header|PicoLisp}}==
<
(wait 2000) # Wait for 2 seconds
(prinl "Awake!")</
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
<
(call 'sleep 2) # Wait for 2 seconds
(prinl "Awake!")</
=={{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">
put ('sleeping');
delay (2000); /* wait for 2 seconds (=2000 milliseconds). */
put ('awake');
</syntaxhighlight>
=={{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}}==
<
Write-Host Sleeping ...
Start-Sleep $d
Write-Host Awake!</
The <code>-Milliseconds</code> parameter to <code>Start-Sleep</code> can be used to allow for sub-second precision in sleeping.
=={{header|Prolog}}==
Works with SWI-Prolog.
<
writeln('Sleeping...'),
sleep(Time),
writeln('Awake!').
</syntaxhighlight>
=={{header|PureBasic}}==
Sleeping is performed with Delay() and a value in milliseconds. The time is accurate to approximately +/- 15 milliseconds.
<
Print("Enter a time(milliseconds) to sleep: ")
Line 1,655 ⟶ 2,117:
Input()
CloseConsole()
EndIf</
=={{header|Python}}==
<
seconds = float(raw_input())
print "Sleeping..."
time.sleep(seconds) # number is in seconds ... but accepts fractions
print "Awake!"</
=={{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">
sleep <- function(time=1)
{
Line 1,678 ⟶ 2,140:
sleep()
</syntaxhighlight>
=={{header|Racket}}==
<
#lang racket
(displayln "Enter a time (in seconds): ")
Line 1,689 ⟶ 2,151:
(sleep time)
(displayln "Awake!"))
</syntaxhighlight>
=={{header|Raku}}==
Line 1,696 ⟶ 2,158:
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"
say "Sleeping...";
sleep $sec;
say "Awake!";</
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}}==
<
Title: "Sleep Main Thread"
URL: http://rosettacode.org/wiki/Sleep_the_Main_Thread
Line 1,720 ⟶ 2,182:
print "Sleeping..."
wait naptime
print "Awake!"</
=={{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"</
=={{header|Retro}}==
Retro has no fine grained timer; so we have to make due with seconds.
<
[ time [ time over - 1 > ] until drop ] times ;
: test
"\nTime to sleep (in seconds): " puts getToken toNumber
"\nSleeping..." sleep
"\nAwake!\n" ;</
=={{header|REXX}}==
Line 1,746 ⟶ 2,208:
Note: the above two REXX interpreters support fractional seconds.
<
parse arg secs . /*obtain optional argument from the CL.*/
if secs=='' | secs=="," then secs=0 /*Not specified? Then assume 0 (zero).*/
Line 1,752 ⟶ 2,214:
call delay secs /*Snooze. Hopefully, just a short nap.*/
say 'Awake!' /*and now inform invoker we're running.*/
/*stick a fork in it, we're all done. */</
'''output''' when using the following for input: <tt> 4.7 </tt>
<pre>
Line 1,776 ⟶ 2,238:
This REXX program only uses whole seconds (fractional seconds are ignored).
<
trace off /*suppress REXX error messages. */
parse arg ! /*obtain all the arguments. */
Line 1,828 ⟶ 2,290:
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)</
Coding note: the '''!''' subroutines (above) deal mostly with determining what version of REXX is being invoked and what operating system is being used; and based on that information, appropriate flags (variables) are set. 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.
Line 1,836 ⟶ 2,298:
=={{header|Ring}}==
<
load "guilib.ring"
Line 1,849 ⟶ 2,311:
oTest = new qTest
oTest.qsleep(nTime)
</syntaxhighlight>
Output:
Line 1,855 ⟶ 2,317:
<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}}==
<
puts "Sleeping..."
sleep(seconds) # number is in seconds ... but accepts fractions
# Minimum resolution is system dependent.
puts "Awake!"</
=={{header|Rust}}==
<
fn main() {
Line 1,883 ⟶ 2,368:
thread::sleep(sleep_duration);
println!("Awake!");
}</
=={{header|Scala}}==
{{libheader|Scala}}<
print("Enter sleep time in milli sec: ")
val ms = scala.io.StdIn.readInt()
Line 1,893 ⟶ 2,378:
Thread.sleep(ms)
println(s"Awaked after [${scala.compat.Platform.currentTime - sleepStarted} ms]1")
}</
=={{header|Scheme}}==
Line 1,900 ⟶ 2,385:
The following works in Chicken Scheme:
<
(use format)
(use srfi-18)
Line 1,912 ⟶ 2,397:
(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.
Line 1,920 ⟶ 2,405:
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.
<
include "duration.s7i";
Line 1,932 ⟶ 2,417:
wait(secondsToSleep . SECONDS);
writeln("Awake!");
end func;</
=={{header|SenseTalk}}==
SenseTalk understands time durations expressed in any units, including: seconds, minutes, days, microseconds, shakes, and jiffies!
<
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
Line 1,951 ⟶ 2,436:
put "Awake!"
</syntaxhighlight>
=={{header|Sidef}}==
<
say "Sleeping...";
Sys.sleep(sec); # in seconds
#Sys.usleep(sec); # in microseconds
#Sys.nanosleep(sec); # in nanoseconds
say "Awake!";</
=={{header|Smalltalk}}==
{{works with|Pharo}}
<
Transcript show: 'Sleeping...'.
(Delay forSeconds: t) wait.
Transcript show: 'Awake!'.
</syntaxhighlight>
{{works with|Smalltalk/X}}
<
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}}==
<
let val seconds = valOf (Int.fromString (valOf (TextIO.inputLine TextIO.stdIn))) in
TextIO.print "Sleeping...\n";
Line 1,984 ⟶ 2,504:
I dunno why; it doesn't say anything about this in the documentation *)
TextIO.print "Awake!\n"
end)</
=={{header|Stata}}==
<
* pass duration in milliseconds
display "Sleeping..."
Line 1,994 ⟶ 2,514:
end
sleep_awake 2000</
=={{header|Suneido}}==
<
{
Print("Sleeping...")
Sleep(time) // time is in milliseconds
Print("Awake!")
}</
=={{header|Swift}}==
<
println("Enter number of seconds to sleep")
Line 2,014 ⟶ 2,534:
NSThread.sleepForTimeInterval(interval)
println("Awake!")</
=={{header|Tcl}}==
Blocking example (the process is blocked preventing any background activity).
<
flush stdout
set millis [gets stdin]
puts Sleeping...
after $millis
puts Awake!</
A non-blocking example where background activity will occur.
<
flush stdout
set millis [gets stdin]
Line 2,033 ⟶ 2,553:
after $millis set ::wakeupflag 1
vwait ::wakeupflag
puts Awake!</
=={{header|TI-89 BASIC}}==
Line 2,064 ⟶ 2,584:
=={{header|TUSCRIPT}}==
<
$$ MODE TUSCRIPT
secondsrange=2
Line 2,070 ⟶ 2,590:
WAIT #secondsrange
PRINT "Awake after Naping ",secondsrange, " seconds"
</syntaxhighlight>
=={{header|TXR}}==
<
(tointz (get-line)))))
(put-string "Sleeping ... ")
(flush-stream)
(usleep usec)
(put-line "Awake!"))</
=={{header|UNIX Shell}}==
<
read seconds
echo "Sleeping..."
sleep "$seconds"
echo "Awake!"</
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}}==
<
# sleep for 5 seconds (5000 milliseconds)
sleep 5000
out "Awake!" endl console</
=={{header|VBA}}==
<syntaxhighlight lang="vba">
Function Sleep(iSecsWait As Integer)
Debug.Print Now(), "Sleeping..."
Line 2,103 ⟶ 2,623:
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}}==
<
Message("Sleeping...\n")
Sleep(#1)
Message("Awake!\n")</
=={{header|Visual Basic .NET}}==
<
Sub Main()
Dim millisecondsSleepTime = Integer.Parse(Console.ReadLine(), Globalization.CultureInfo.CurrentCulture)
Line 2,130 ⟶ 2,650:
Console.WriteLine("Awake!")
End Sub
End Module</
=={{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.
<
; x86_64 linux nasm
Line 2,151 ⟶ 2,754:
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}}==
<
const time = std
const warn = std.debug.warn;
Line 2,164 ⟶ 2,775:
warn("Awake!\n");
}</
=={{header|zkl}}==
<
println("Sleeping...");
Atomic.sleep(seconds); # float, usually millisecond resolution
println("Awake!");</
=={{header|Zoomscript}}==
For typing:
<
wait 1
println
print "Awake!"</
For importing:
|