Sleep: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
Line 17: Line 17:
{{trans|Python}}
{{trans|Python}}


<lang 11l>V seconds = Float(input())
<syntaxhighlight lang="11l">V seconds = Float(input())
print(‘Sleeping...’)
print(‘Sleeping...’)
sleep(seconds)
sleep(seconds)
print(‘Awake!’)</lang>
print(‘Awake!’)</syntaxhighlight>


=={{header|360 Assembly}}==
=={{header|360 Assembly}}==
REENTRANT means the program can be called from several callers simultaneously. The program obtains storage (memory) at each invocation.
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)
Sleep (logically swapped out task) is established through STIMER macro (SVC 47)
<syntaxhighlight lang="360 assembly">
<lang 360 Assembly>
START
START
PRINT DATA,GEN
PRINT DATA,GEN
Line 132: Line 132:
* --------------------------------------------------------------------
* --------------------------------------------------------------------
END SLEEP
END SLEEP
</syntaxhighlight>
</lang>
'''output''' invoked with PARM='6' (+ sign indicates "problem state" (non system key) execution
'''output''' invoked with PARM='6' (+ sign indicates "problem state" (non system key) execution
<pre style="overflow:scroll">
<pre style="overflow:scroll">
Line 141: Line 141:
=={{header|8051 Assembly}}==
=={{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.
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.
<lang asm>ORG RESET
<syntaxhighlight lang="asm">ORG RESET
jmp main
jmp main
ORG TIMER0
ORG TIMER0
Line 163: Line 163:


; Awake!
; Awake!
jmp $</lang>
jmp $</syntaxhighlight>


=={{header|8th}}==
=={{header|8th}}==
<lang forth>
<syntaxhighlight lang="forth">
f:stdin f:getline
f:stdin f:getline
"Sleeping..." . cr
"Sleeping..." . cr
eval sleep
eval sleep
"Awake!" . cr bye
"Awake!" . cr bye
</syntaxhighlight>
</lang>
=={{header|AArch64 Assembly}}==
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program sleep64.s */
/* program sleep64.s */
Line 263: Line 263:
/* for this file see task include a file in language AArch64 assembly */
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>
<pre>
<pre>
Enter the time to sleep in seconds : 5
Enter the time to sleep in seconds : 5
Line 271: Line 271:
</pre>
</pre>
=={{header|Action!}}==
=={{header|Action!}}==
<lang Action!>BYTE RTCLOK1=$13
<syntaxhighlight lang="action!">BYTE RTCLOK1=$13
BYTE RTCLOK2=$14
BYTE RTCLOK2=$14
BYTE PALNTSC=$D014
BYTE PALNTSC=$D014
Line 340: Line 340:
PrintF("Waited %U-%U=%U frames / %U ms%E%E",end,beg,diff,diffMs)
PrintF("Waited %U-%U=%U frames / %U ms%E%E",end,beg,diff,diffMs)
OD
OD
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
The following result has been obtained from PAL version of Atari 8-bit computer.
The following result has been obtained from PAL version of Atari 8-bit computer.
Line 381: Line 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.
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.


<lang ada>with Ada.Text_Io; use Ada.Text_Io;
<syntaxhighlight lang="ada">with Ada.Text_Io; use Ada.Text_Io;
with Ada.Float_Text_Io; use Ada.Float_Text_Io;
with Ada.Float_Text_Io; use Ada.Float_Text_Io;
Line 391: Line 391:
delay Duration(In_Val);
delay Duration(In_Val);
Put_Line("Awake!");
Put_Line("Awake!");
end Sleep;</lang>
end Sleep;</syntaxhighlight>


=={{header|Aime}}==
=={{header|Aime}}==
<lang aime>o_text("Sleeping...\n");
<syntaxhighlight lang="aime">o_text("Sleeping...\n");


# Sleep X seconds
# Sleep X seconds
Line 402: Line 402:
#usleep(atoi(argv(1)));
#usleep(atoi(argv(1)));


o_text("Awake!\n");</lang>
o_text("Awake!\n");</syntaxhighlight>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
Line 408: Line 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]}}
{{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.
Only works for Microsoft Windows because it uses Windows-specific ping syntax.
<lang algol68># using ping to sleep #
<syntaxhighlight lang="algol68"># using ping to sleep #
INT milliseconds = read int; # ping uses milliseconds #
INT milliseconds = read int; # ping uses milliseconds #
print ("Sleeping...");
print ("Sleeping...");
Line 415: Line 415:
# ping -n gives number of tries, -w timeout, and >NUL deletes output so the user does not see it #
# ping -n gives number of tries, -w timeout, and >NUL deletes output so the user does not see it #
print (new line);
print (new line);
print ("Awake!")</lang>
print ("Awake!")</syntaxhighlight>


=={{header|AntLang}}==
=={{header|AntLang}}==
<lang AntLang>milliseconds: eval[input["How long should I sleep? "]] / eval = evil, but this is just a simple demo
<syntaxhighlight lang="antlang">milliseconds: eval[input["How long should I sleep? "]] / eval = evil, but this is just a simple demo
echo["Sleeping..."]
echo["Sleeping..."]
sleep[milliseconds]
sleep[milliseconds]
echo["Awake!"]</lang>
echo["Awake!"]</syntaxhighlight>


=={{header|Applesoft BASIC}}==
=={{header|Applesoft BASIC}}==
The cycles and times calculated should only be taken as a minimum delay.
The cycles and times calculated should only be taken as a minimum delay.
<lang ApplesoftBasic> 10 POKE 768,169: POKE 770,76
<syntaxhighlight lang="applesoftbasic"> 10 POKE 768,169: POKE 770,76
20 POKE 771,168: POKE 772,252
20 POKE 771,168: POKE 772,252
30 INPUT "ENTER WAIT VALUE (1-256) : ";A
30 INPUT "ENTER WAIT VALUE (1-256) : ";A
Line 433: Line 433:
70 PRINT "WAIT FOR "C" CYCLES OR "
70 PRINT "WAIT FOR "C" CYCLES OR "
80 PRINT C * 14 / 14.318181" MICROSECONDS"
80 PRINT C * 14 / 14.318181" MICROSECONDS"
90 PRINT "SLEEPING": CALL 768: PRINT "AWAKE"</lang>
90 PRINT "SLEEPING": CALL 768: PRINT "AWAKE"</syntaxhighlight>
Output:<pre>ENTER WAIT VALUE (1-256) : 256
Output:<pre>ENTER WAIT VALUE (1-256) : 256
WAIT FOR 167309 CYCLES OR
WAIT FOR 167309 CYCLES OR
Line 443: Line 443:
=={{header|ARM Assembly}}==
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>


/* ARM assembly Raspberry PI */
/* ARM assembly Raspberry PI */
Line 609: Line 609:
.align 4
.align 4


</syntaxhighlight>
</lang>


=={{header|Arturo}}==
=={{header|Arturo}}==
<lang rebol>time: to :integer input "Enter number of milliseconds: "
<syntaxhighlight lang="rebol">time: to :integer input "Enter number of milliseconds: "
print "Sleeping..."
print "Sleeping..."
pause time
pause time
print "Awake!"</lang>
print "Awake!"</syntaxhighlight>


{{out}}
{{out}}
Line 624: Line 624:


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>TrayTip, sleeping, sleeping
<syntaxhighlight lang="autohotkey">TrayTip, sleeping, sleeping
sleep, 2000 ; 2 seconds
sleep, 2000 ; 2 seconds
TrayTip, awake, awake
TrayTip, awake, awake
Msgbox, awake</lang>
Msgbox, awake</syntaxhighlight>


=={{header|AutoIt}}==
=={{header|AutoIt}}==
<lang AutoIt>#AutoIt Version: 3.2.10.0
<syntaxhighlight lang="autoit">#AutoIt Version: 3.2.10.0
$sleep_me=InputBox("Sleep", "Number of seconds to sleep", "10", "", -1, -1, 0, 0)
$sleep_me=InputBox("Sleep", "Number of seconds to sleep", "10", "", -1, -1, 0, 0)
Dim $sleep_millisec=$sleep_me*1000
Dim $sleep_millisec=$sleep_me*1000
MsgBox(0,"Sleep","Sleeping for "&$sleep_me&" sec")
MsgBox(0,"Sleep","Sleeping for "&$sleep_me&" sec")
sleep ($sleep_millisec)
sleep ($sleep_millisec)
MsgBox(0,"Awake","... Awaking")</lang>
MsgBox(0,"Awake","... Awaking")</syntaxhighlight>


=={{header|AWK}}==
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f SLEEP.AWK [seconds]
# syntax: GAWK -f SLEEP.AWK [seconds]
BEGIN {
BEGIN {
Line 651: Line 651:
while (systime() < t + seconds) {}
while (systime() < t + seconds) {}
}
}
</syntaxhighlight>
</lang>
<p>commands and output:</p>
<p>commands and output:</p>
<pre>
<pre>
Line 667: Line 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.
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.


<lang axe>Disp "TIME:"
<syntaxhighlight lang="axe">Disp "TIME:"
input→A
input→A
0→T
0→T
Line 681: Line 681:
Disp "SLEEPING...",i
Disp "SLEEPING...",i
Pause T
Pause T
Disp "AWAKE",i</lang>
Disp "AWAKE",i</syntaxhighlight>


=={{header|BASIC}}==
=={{header|BASIC}}==
{{works with|QuickBasic|4.5}}
{{works with|QuickBasic|4.5}}
<lang qbasic>INPUT sec 'the SLEEP command takes seconds
<syntaxhighlight lang="qbasic">INPUT sec 'the SLEEP command takes seconds
PRINT "Sleeping..."
PRINT "Sleeping..."
SLEEP sec
SLEEP sec
PRINT "Awake!"</lang>
PRINT "Awake!"</syntaxhighlight>
"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.
"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}}===
==={{header|BASIC256}}===
<lang basic256>print "Enter number of seconds to sleep: ";
<syntaxhighlight lang="basic256">print "Enter number of seconds to sleep: ";
input ms
input ms
print "Sleeping..."
print "Sleeping..."
pause ms
pause ms
print "Awake!"
print "Awake!"
end</lang>
end</syntaxhighlight>


==={{header|True BASIC}}===
==={{header|True BASIC}}===
<lang QBasic>PRINT "Enter number of seconds to sleep";
<syntaxhighlight lang="qbasic">PRINT "Enter number of seconds to sleep";
INPUT ms
INPUT ms
PRINT "Sleeping..."
PRINT "Sleeping..."
PAUSE ms
PAUSE ms
PRINT "Awake!"
PRINT "Awake!"
END</lang>
END</syntaxhighlight>


==={{header|Yabasic}}===
==={{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.
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.
<lang yabasic>input "Enter number of seconds to sleep: " ms
<syntaxhighlight lang="yabasic">input "Enter number of seconds to sleep: " ms
print "Sleeping..."
print "Sleeping..."


Line 717: Line 717:


print "Awake!"
print "Awake!"
end</lang>
end</syntaxhighlight>


==={{header|Sinclair ZX81 BASIC}}===
==={{header|Sinclair ZX81 BASIC}}===
Line 738: Line 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>)
(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>)


<lang basic>10 PRINT "HOW LONG SHOULD I SLEEP FOR?"
<syntaxhighlight lang="basic">10 PRINT "HOW LONG SHOULD I SLEEP FOR?"
20 PRINT "(IN TELEVISION FRAMES)"
20 PRINT "(IN TELEVISION FRAMES)"
30 INPUT SLEEPTIME
30 INPUT SLEEPTIME
40 PRINT "SLEEPING... ";
40 PRINT "SLEEPING... ";
50 PAUSE SLEEPTIME
50 PAUSE SLEEPTIME
60 PRINT "AWAKE."</lang>
60 PRINT "AWAKE."</syntaxhighlight>


==={{header|BaCon}}===
==={{header|BaCon}}===


<lang freebasic>
<syntaxhighlight lang="freebasic">
'---The SLEEP command takes milliseconds by default but we will adjust it
'---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 "
PRINT "Enter a number for each second you want to wait\nthen press Enter "
Line 754: Line 754:
SLEEP millisec * 1000
SLEEP millisec * 1000
PRINT "Awake!"
PRINT "Awake!"
</lang>
</syntaxhighlight>


==={{header|ZX Spectrum Basic}}===
==={{header|ZX Spectrum Basic}}===
Line 760: Line 760:
Pressing a key will cut the pause short on the ZX Spectrum.
Pressing a key will cut the pause short on the ZX Spectrum.


<lang zxbasic>10 REM s is the number of seconds
<syntaxhighlight lang="zxbasic">10 REM s is the number of seconds
20 LET s = 5
20 LET s = 5
30 PRINT "Sleeping"
30 PRINT "Sleeping"
40 PAUSE s * 50
40 PAUSE s * 50
50 PRINT "Awake"</lang>
50 PRINT "Awake"</syntaxhighlight>


=={{header|Batch File}}==
=={{header|Batch File}}==
Line 770: Line 770:


{{works with|Windows NT|4}}
{{works with|Windows NT|4}}
<lang dos>@echo off
<syntaxhighlight lang="dos">@echo off
set /p Seconds=Enter the number of seconds to sleep:
set /p Seconds=Enter the number of seconds to sleep:
set /a Seconds+=1
set /a Seconds+=1
echo Sleeping ...
echo Sleeping ...
ping -n %Seconds% localhost >nul 2>&1
ping -n %Seconds% localhost >nul 2>&1
echo Awake!</lang>
echo Awake!</syntaxhighlight>
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:
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}}
{{works with|Windows 2000}}
<lang dos>@echo off
<syntaxhighlight lang="dos">@echo off
set /p MilliSeconds=Enter the number of milliseconds to sleep:
set /p MilliSeconds=Enter the number of milliseconds to sleep:
echo Sleeping ...
echo Sleeping ...
ping -n 1 -w %MilliSeconds% 1.2.3.4 >nul 2>&1
ping -n 1 -w %MilliSeconds% 1.2.3.4 >nul 2>&1
echo Awake!</lang>
echo Awake!</syntaxhighlight>


Starting with Windows Vista there is a command-line utility to wait a number of seconds:
Starting with Windows Vista there is a command-line utility to wait a number of seconds:


{{works with|Windows Vista}}
{{works with|Windows Vista}}
<lang dos>@echo off
<syntaxhighlight lang="dos">@echo off
set /p Seconds=Enter the number of seconds to sleep:
set /p Seconds=Enter the number of seconds to sleep:
echo Sleeping ...
echo Sleeping ...
timeout /t %Seconds% /nobreak >nul
timeout /t %Seconds% /nobreak >nul
echo Awake!</lang>
echo Awake!</syntaxhighlight>


=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
<lang bbcbasic> INPUT "Enter the time to sleep in centiseconds: " sleep%
<syntaxhighlight lang="bbcbasic"> INPUT "Enter the time to sleep in centiseconds: " sleep%
PRINT "Sleeping..."
PRINT "Sleeping..."
WAIT sleep%
WAIT sleep%
PRINT "Awake!"</lang>
PRINT "Awake!"</syntaxhighlight>
Whilst sleeping BBC BASIC for Windows periodically tests for the ESCape key being pressed.
Whilst sleeping BBC BASIC for Windows periodically tests for the ESCape key being pressed.


Line 808: Line 808:
The function <tt>sleep</tt> needs seconds, which are read from the standard input.
The function <tt>sleep</tt> needs seconds, which are read from the standard input.


<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <unistd.h>
#include <unistd.h>


Line 819: Line 819:
printf("Awake!\n");
printf("Awake!\n");
return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==


<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;
using System.Threading;
using System.Threading;


Line 835: Line 835:
Console.WriteLine("Awake!");
Console.WriteLine("Awake!");
}
}
}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
Line 841: Line 841:
{{works with|C++11}}
{{works with|C++11}}


<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>
#include <thread>
#include <thread>
#include <chrono>
#include <chrono>
Line 852: Line 852:
std::cout << "Awake!\n";
std::cout << "Awake!\n";
}
}
</syntaxhighlight>
</lang>


{{works with|POSIX}}
{{works with|POSIX}}


<lang cpp>#include <unistd.h>
<syntaxhighlight lang="cpp">#include <unistd.h>
#include <iostream>
#include <iostream>


Line 869: Line 869:
cout << "Awake!" << endl;
cout << "Awake!" << endl;
return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|Caché ObjectScript}}==
=={{header|Caché ObjectScript}}==
<syntaxhighlight lang="caché objectscript">
<lang Caché ObjectScript>
SLEEP
SLEEP
; the HANG command can use fractional seconds; the Awake line will be slightly off due to processing time
; the HANG command can use fractional seconds; the Awake line will be slightly off due to processing time
Line 880: Line 880:
write !,"Awake! Time is "_$ztime($piece($ztimestamp,",",2,2),1,2)
write !,"Awake! Time is "_$ztime($piece($ztimestamp,",",2,2),1,2)
quit
quit
</syntaxhighlight>
</lang>


{{out}}<pre>
{{out}}<pre>
Line 890: Line 890:


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang clojure>(defn sleep [ms] ; time in milliseconds
<syntaxhighlight lang="clojure">(defn sleep [ms] ; time in milliseconds
(println "Sleeping...")
(println "Sleeping...")
(Thread/sleep ms)
(Thread/sleep ms)
(println "Awake!"))
(println "Awake!"))
; call it
; call it
(sleep 1000)</lang>
(sleep 1000)</syntaxhighlight>


=={{header|COBOL}}==
=={{header|COBOL}}==
Line 902: Line 902:
{{works with|ACUCOBOL-GT}}
{{works with|ACUCOBOL-GT}}
{{works with|OpenCOBOL}}
{{works with|OpenCOBOL}}
<lang cobol> IDENTIFICATION DIVISION.
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. Sleep-In-Seconds.
PROGRAM-ID. Sleep-In-Seconds.


Line 919: Line 919:


GOBACK
GOBACK
.</lang>
.</syntaxhighlight>


While the second expects the time to be in nanoseconds. Note: Windows systems can only sleep to the nearest millisecond.
While the second expects the time to be in nanoseconds. Note: Windows systems can only sleep to the nearest millisecond.
{{works with|OpenCOBOL}}
{{works with|OpenCOBOL}}
<lang cobol> IDENTIFICATION DIVISION.
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. Sleep-In-Nanoseconds.
PROGRAM-ID. Sleep-In-Nanoseconds.


Line 945: Line 945:


GOBACK
GOBACK
.</lang>
.</syntaxhighlight>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<lang lisp>(defun test-sleep ()
<syntaxhighlight lang="lisp">(defun test-sleep ()
(let ((seconds (read)))
(let ((seconds (read)))
(format t "Sleeping...~%")
(format t "Sleeping...~%")
Line 954: Line 954:
(format t "Awake!~%")))
(format t "Awake!~%")))


(test-sleep)</lang>
(test-sleep)</syntaxhighlight>


=={{header|D}}==
=={{header|D}}==
<lang d>import std.stdio, core.thread;
<syntaxhighlight lang="d">import std.stdio, core.thread;


void main() {
void main() {
Line 968: Line 968:
Thread.sleep(dur!"seconds"(secs));
Thread.sleep(dur!"seconds"(secs));
writeln("Awake!");
writeln("Awake!");
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Enter a time to sleep (in seconds): 5
<pre>Enter a time to sleep (in seconds): 5
Line 975: Line 975:


=={{header|DCL}}==
=={{header|DCL}}==
<lang DCL>$ amount_of_time = p1 ! hour[:[minute][:[second][.[hundredth]]]]
<syntaxhighlight lang="dcl">$ amount_of_time = p1 ! hour[:[minute][:[second][.[hundredth]]]]
$ write sys$output "Sleeping..."
$ write sys$output "Sleeping..."
$ wait 'amount_of_time
$ wait 'amount_of_time
$ write sys$output "Awake!"</lang>
$ write sys$output "Awake!"</syntaxhighlight>
{{out}}
{{out}}
<pre>$ @sleep 1 ! sleeps for 1 hour
<pre>$ @sleep 1 ! sleeps for 1 hour
Line 997: Line 997:


=={{header|DBL}}==
=={{header|DBL}}==
<syntaxhighlight lang="dbl">;
<lang DBL>;
; Sleep for DBL version 4 by Dario B.
; Sleep for DBL version 4 by Dario B.
;
;
Line 1,008: Line 1,008:
SLEEP 10 ;Sleep for 10 seconds
SLEEP 10 ;Sleep for 10 seconds
DISPLAY (1,"Awake!",10)
DISPLAY (1,"Awake!",10)
</syntaxhighlight>
</lang>


=={{header|Delphi}}==
=={{header|Delphi}}==
<lang Delphi>program SleepOneSecond;
<syntaxhighlight lang="delphi">program SleepOneSecond;


{$APPTYPE CONSOLE}
{$APPTYPE CONSOLE}
Line 1,027: Line 1,027:
Sleep(lTimeToSleep); // milliseconds
Sleep(lTimeToSleep); // milliseconds
WriteLn('Awake!');
WriteLn('Awake!');
end.</lang>
end.</syntaxhighlight>


=={{header|Diego}}==
=={{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.
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.
<lang diego>begin_instuct(sleepTime);
<syntaxhighlight lang="diego">begin_instuct(sleepTime);
ask_human()_first()_msg(Enter number of seconds to sleep: )_var(sleepSecs)_me();
ask_human()_first()_msg(Enter number of seconds to sleep: )_var(sleepSecs)_me();
set_decision(asynchronous)_me();
set_decision(asynchronous)_me();
Line 1,041: Line 1,041:


exec_instruct(sleepTime)_me();
exec_instruct(sleepTime)_me();
</syntaxhighlight>
</lang>


=={{header|DIBOL-11}}==
=={{header|DIBOL-11}}==
<syntaxhighlight lang="dibol-11">
<lang DIBOL-11>


START ;Demonstrate the SLEEP function
START ;Demonstrate the SLEEP function
Line 1,065: Line 1,065:




</syntaxhighlight>
</lang>
=={{header|E}}==
=={{header|E}}==


Line 1,074: Line 1,074:
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.
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.


<lang e>def sleep(milliseconds :int, nextThing) {
<syntaxhighlight lang="e">def sleep(milliseconds :int, nextThing) {
stdout.println("Sleeping...")
stdout.println("Sleeping...")
timer.whenPast(timer.now() + milliseconds, fn {
timer.whenPast(timer.now() + milliseconds, fn {
Line 1,080: Line 1,080:
nextThing()
nextThing()
})
})
}</lang>
}</syntaxhighlight>


=={{header|EGL}}==
=={{header|EGL}}==
<lang EGL>program Sleep type BasicProgram{}
<syntaxhighlight lang="egl">program Sleep type BasicProgram{}


// Syntax: sysLib.wait(time BIN(9,2) in)
// Syntax: sysLib.wait(time BIN(9,2) in)
Line 1,093: Line 1,093:
end
end


end</lang>
end</syntaxhighlight>


=={{header|Eiffel}}==
=={{header|Eiffel}}==
Line 1,101: Line 1,101:
<code lang="eiffel">sleep</code> takes an argument which declares the number of nanoseconds to suspend the thread's execution.
<code lang="eiffel">sleep</code> takes an argument which declares the number of nanoseconds to suspend the thread's execution.


<lang eiffel >class
<syntaxhighlight lang="eiffel ">class
APPLICATION
APPLICATION
inherit
inherit
Line 1,117: Line 1,117:
print ("Awake!%N")
print ("Awake!%N")
end
end
end</lang>
end</syntaxhighlight>


Output (sleeping 10 seconds):
Output (sleeping 10 seconds):
Line 1,128: Line 1,128:
=={{header|Elena}}==
=={{header|Elena}}==
ELENA 4.x :
ELENA 4.x :
<lang elena>import extensions;
<syntaxhighlight lang="elena">import extensions;
public program()
public program()
Line 1,136: Line 1,136:
system'threading'threadControl.sleep(sleep);
system'threading'threadControl.sleep(sleep);
console.printLine("Awake!")
console.printLine("Awake!")
}</lang>
}</syntaxhighlight>


=={{header|Elixir}}==
=={{header|Elixir}}==
<lang elixir>sleep = fn seconds ->
<syntaxhighlight lang="elixir">sleep = fn seconds ->
IO.puts "Sleeping..."
IO.puts "Sleeping..."
:timer.sleep(1000 * seconds) # in milliseconds
:timer.sleep(1000 * seconds) # in milliseconds
Line 1,146: Line 1,146:


sec = if System.argv==[], do: 1, else: hd(System.argv) |> String.to_integer
sec = if System.argv==[], do: 1, else: hd(System.argv) |> String.to_integer
sleep.(sec)</lang>
sleep.(sec)</syntaxhighlight>


=={{header|Emacs Lisp}}==
=={{header|Emacs Lisp}}==
<lang lisp>(let ((seconds (read-number "Time in seconds: ")))
<syntaxhighlight lang="lisp">(let ((seconds (read-number "Time in seconds: ")))
(message "Sleeping ...")
(message "Sleeping ...")
(sleep-for seconds)
(sleep-for seconds)
(message "Awake!"))</lang>
(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.
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.
Line 1,159: Line 1,159:


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:
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:
<lang erlang>main() ->
<syntaxhighlight lang="erlang">main() ->
io:format("Sleeping...~n"),
io:format("Sleeping...~n"),
timer:sleep(1000), %% in milliseconds
timer:sleep(1000), %% in milliseconds
io:format("Awake!~n").</lang>
io:format("Awake!~n").</syntaxhighlight>


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:
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:
<lang erlang>main() ->
<syntaxhighlight lang="erlang">main() ->
io:format("Sleeping...~n"),
io:format("Sleeping...~n"),
receive
receive
after 1000 -> ok %% in milliseconds
after 1000 -> ok %% in milliseconds
end,
end,
io:format("Awake!~n").</lang>
io:format("Awake!~n").</syntaxhighlight>


which is the way it is implemented in the <tt>timer</tt> module.
which is the way it is implemented in the <tt>timer</tt> module.


=={{header|ERRE}}==
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
..............
..............
INPUT("Enter the time to sleep in seconds: ";sleep)
INPUT("Enter the time to sleep in seconds: ";sleep)
Line 1,182: Line 1,182:
PRINT("Awake!")
PRINT("Awake!")
..............
..............
</syntaxhighlight>
</lang>


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
{{trans|C#}}
{{trans|C#}}
<lang fsharp>open System
<syntaxhighlight lang="fsharp">open System
open System.Threading
open System.Threading
Line 1,195: Line 1,195:
Thread.Sleep(sleep); //milliseconds
Thread.Sleep(sleep); //milliseconds
Console.WriteLine("Awake!")
Console.WriteLine("Awake!")
0</lang>
0</syntaxhighlight>


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>USING: calendar io math.parser threads ;
<syntaxhighlight lang="factor">USING: calendar io math.parser threads ;


: read-sleep ( -- )
: read-sleep ( -- )
Line 1,204: Line 1,204:
"Sleeping..." print
"Sleeping..." print
sleep
sleep
"Awake!" print ;</lang>
"Awake!" print ;</syntaxhighlight>


=={{header|Fantom}}==
=={{header|Fantom}}==
Line 1,210: Line 1,210:
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.
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.


<lang fantom>
<syntaxhighlight lang="fantom">
using concurrent
using concurrent


Line 1,232: Line 1,232:
}
}
}
}
</syntaxhighlight>
</lang>


Output:
Output:
Line 1,243: Line 1,243:


=={{header|FBSL}}==
=={{header|FBSL}}==
<lang qbasic>#APPTYPE CONSOLE
<syntaxhighlight lang="qbasic">#APPTYPE CONSOLE
DIM %msec
DIM %msec
PRINT "Milliseconds to sleep: ";
PRINT "Milliseconds to sleep: ";
Line 1,251: Line 1,251:
PRINT "Awake!"
PRINT "Awake!"
PAUSE
PAUSE
</syntaxhighlight>
</lang>
Output
Output
<pre>Milliseconds to sleep: 1000
<pre>Milliseconds to sleep: 1000
Line 1,260: Line 1,260:


=={{header|Forth}}==
=={{header|Forth}}==
<lang forth>: sleep ( ms -- )
<syntaxhighlight lang="forth">: sleep ( ms -- )
." Sleeping..."
." Sleeping..."
ms
ms
." awake." cr ;</lang>
." awake." cr ;</syntaxhighlight>


====Explanation note on MS====
====Explanation note on MS====
Line 1,272: Line 1,272:


=={{header|Fortran}}==
=={{header|Fortran}}==
<lang fortran>program test_sleep
<syntaxhighlight lang="fortran">program test_sleep


implicit none
implicit none
Line 1,289: Line 1,289:
end if
end if


end program test_sleep</lang>
end program test_sleep</syntaxhighlight>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64


Dim ms As UInteger
Dim ms As UInteger
Line 1,299: Line 1,299:
Sleep ms, 1 '' the "1" means Sleep can't be interrupted with a keystroke
Sleep ms, 1 '' the "1" means Sleep can't be interrupted with a keystroke
Print "Awake!"
Print "Awake!"
End</lang>
End</syntaxhighlight>


Sample input/output
Sample input/output
Line 1,311: Line 1,311:
=={{header|Frink}}==
=={{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.
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.
<lang frink>
<syntaxhighlight lang="frink">
do
do
t = eval[input["Enter amount of time to sleep: ", "1 second"]]
t = eval[input["Enter amount of time to sleep: ", "1 second"]]
Line 1,319: Line 1,319:
sleep[t]
sleep[t]
println["Awake!"]
println["Awake!"]
</syntaxhighlight>
</lang>


=={{header|Go}}==
=={{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.
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.
<lang go>package main
<syntaxhighlight lang="go">package main


import "time"
import "time"
Line 1,335: Line 1,335:
time.Sleep(time.Duration(sec * float64(time.Second)))
time.Sleep(time.Duration(sec * float64(time.Second)))
fmt.Println("\nAwake!")
fmt.Println("\nAwake!")
}</lang>
}</syntaxhighlight>


=={{header|Groovy}}==
=={{header|Groovy}}==
Solution:
Solution:
<lang groovy>def sleepTest = {
<syntaxhighlight lang="groovy">def sleepTest = {
println("Sleeping...")
println("Sleeping...")
sleep(it)
sleep(it)
println("Awake!")
println("Awake!")
}</lang>
}</syntaxhighlight>


Test:
Test:
<lang groovy>sleepTest(1000)
<syntaxhighlight lang="groovy">sleepTest(1000)
print '''
print '''
Hmmm. That was... less than satisfying.
Hmmm. That was... less than satisfying.
Line 1,357: Line 1,357:
}
}
}
}
sleepTest(5000)</lang>
sleepTest(5000)</syntaxhighlight>


Output:
Output:
Line 1,375: Line 1,375:


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang haskell>import Control.Concurrent
<syntaxhighlight lang="haskell">import Control.Concurrent


main = do seconds <- readLn
main = do seconds <- readLn
putStrLn "Sleeping..."
putStrLn "Sleeping..."
threadDelay $ round $ seconds * 1000000
threadDelay $ round $ seconds * 1000000
putStrLn "Awake!"</lang>
putStrLn "Awake!"</syntaxhighlight>


=={{header|HicEst}}==
=={{header|HicEst}}==
<lang hicest>DLG(NameEdit = milliseconds, Button = "Go to sleep")
<syntaxhighlight lang="hicest">DLG(NameEdit = milliseconds, Button = "Go to sleep")
WRITE(StatusBar) "Sleeping ... "
WRITE(StatusBar) "Sleeping ... "
SYSTEM(WAIT = milliseconds)
SYSTEM(WAIT = milliseconds)
WRITE(Messagebox) "Awake!"</lang>
WRITE(Messagebox) "Awake!"</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
<lang Icon>procedure main()
<syntaxhighlight lang="icon">procedure main()


repeat {
repeat {
Line 1,400: Line 1,400:
delay(1000 * s)
delay(1000 * s)
write("Awake!")
write("Awake!")
end</lang>
end</syntaxhighlight>


=={{header|IDL}}==
=={{header|IDL}}==


<syntaxhighlight lang="idl">
<lang IDL>
read,i,prompt='Input sleep time in seconds: '
read,i,prompt='Input sleep time in seconds: '
print,'Sleeping...'
print,'Sleeping...'
wait,i ; in seconds, but accepts floats(/fractional) as input
wait,i ; in seconds, but accepts floats(/fractional) as input
print,'Awake!'
print,'Awake!'
</syntaxhighlight>
</lang>


=={{header|J}}==
=={{header|J}}==


'''Solution''':
'''Solution''':
<lang j>sleep =: 6!:3
<syntaxhighlight lang="j">sleep =: 6!:3


sleeping=: monad define
sleeping=: monad define
Line 1,420: Line 1,420:
sleep y
sleep y
smoutput 'Awake!'
smoutput 'Awake!'
)</lang>
)</syntaxhighlight>


'''Example''':
'''Example''':
<lang j> sleeping 0.500 NB. Sleep 500 milliseconds
<syntaxhighlight lang="j"> sleeping 0.500 NB. Sleep 500 milliseconds
Sleeping...
Sleeping...
Awake!</lang>
Awake!</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
{{works with|Java|1.5+}}
{{works with|Java|1.5+}}
<lang java5>
<syntaxhighlight lang="java5">
import java.util.InputMismatchException;
import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.Scanner;
Line 1,444: Line 1,444:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
Line 1,451: Line 1,451:
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.
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.


<lang html><script>
<syntaxhighlight lang="html"><script>


setTimeout(function () {
setTimeout(function () {
Line 1,459: Line 1,459:
document.write('Sleeping... ');
document.write('Sleeping... ');


</script></lang>
</script></syntaxhighlight>


=={{header|Jsish}}==
=={{header|Jsish}}==
<lang javascript>/*
<syntaxhighlight lang="javascript">/*
Sleep, in Jsish
Sleep, in Jsish
*/
*/
Line 1,471: Line 1,471:
puts('Sleeping...');
puts('Sleeping...');
sleep(ms);
sleep(ms);
puts('Awake!');</lang>
puts('Awake!');</syntaxhighlight>


=={{header|Julia}}==
=={{header|Julia}}==


<syntaxhighlight lang="julia">
<lang Julia>
print("Please enter sleep duration in seconds: ")
print("Please enter sleep duration in seconds: ")
input = int(readline(STDIN))
input = int(readline(STDIN))
Line 1,481: Line 1,481:
sleep(input)
sleep(input)
println("Awake!")
println("Awake!")
</syntaxhighlight>
</lang>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.0.6
<syntaxhighlight lang="scala">// version 1.0.6


fun main(args: Array<String>) {
fun main(args: Array<String>) {
Line 1,492: Line 1,492:
Thread.sleep(ms)
Thread.sleep(ms)
println("Awake!")
println("Awake!")
}</lang>
}</syntaxhighlight>
Sample input/output:
Sample input/output:
{{out}}
{{out}}
Line 1,509: Line 1,509:
Lasso has a built in sleep command that accepts milliseconds as an input.
Lasso has a built in sleep command that accepts milliseconds as an input.


<lang Lasso>stdoutnl('Sleeping...')
<syntaxhighlight lang="lasso">stdoutnl('Sleeping...')
sleep(5000) // Sleep 5 seconds
sleep(5000) // Sleep 5 seconds
stdoutnl('Awake!')</lang>
stdoutnl('Awake!')</syntaxhighlight>


=={{header|Lhogho}}==
=={{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
The Logo version works without modification. Another way to Sleep, in the Windows version of Lhogho, is to use the Win32 function, viz
<lang logo>make "Void "V0
<syntaxhighlight lang="logo">make "Void "V0
make "Long "U4
make "Long "U4
make "kernel32_handle libload "kernel32.dll
make "kernel32_handle libload "kernel32.dll
Line 1,526: Line 1,526:
Sleep :n ; units: 1/1000th of a second
Sleep :n ; units: 1/1000th of a second
print [Awake.]
print [Awake.]
end</lang>
end</syntaxhighlight>


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
<lang lb>Input "Please input the number of milliseconds you would like to sleep. "; sleeptime
<syntaxhighlight lang="lb">Input "Please input the number of milliseconds you would like to sleep. "; sleeptime
Print "Sleeping..."
Print "Sleeping..."
CallDLL #kernel32, "Sleep", sleeptime As long, ret As void
CallDLL #kernel32, "Sleep", sleeptime As long, ret As void
Print "Awake!"
Print "Awake!"
</syntaxhighlight>
</lang>


=={{header|Lingo}}==
=={{header|Lingo}}==
{{libheader|CommandLine Xtra}}
{{libheader|CommandLine Xtra}}
<lang lingo>on doSleep (ms)
<syntaxhighlight lang="lingo">on doSleep (ms)
put "Sleeping..."
put "Sleeping..."
sleep(ms)
sleep(ms)
put "Awake!"
put "Awake!"
end</lang>
end</syntaxhighlight>


=={{header|Logo}}==
=={{header|Logo}}==
<lang logo>
<syntaxhighlight lang="logo">
to sleep :n
to sleep :n
print [Sleeping...]
print [Sleeping...]
Line 1,550: Line 1,550:
print [Awake.]
print [Awake.]
end
end
</syntaxhighlight>
</lang>


=={{header|Logtalk}}==
=={{header|Logtalk}}==
Works when using SWI-Prolog, XSB, or YAP as the backend compilers:
Works when using SWI-Prolog, XSB, or YAP as the backend compilers:
<lang logtalk>
<syntaxhighlight lang="logtalk">
:- object(sleep).
:- object(sleep).


Line 1,565: Line 1,565:


:- end_object.
:- end_object.
</syntaxhighlight>
</lang>
Sample output:
Sample output:
<lang text>
<syntaxhighlight lang="text">
| ?- sleep::how_long(5).
| ?- sleep::how_long(5).
Sleeping ...
Sleeping ...
... awake!
... awake!
yes
yes
</syntaxhighlight>
</lang>


=={{header|Lua}}==
=={{header|Lua}}==
{{libheader|LuaSocket}}
{{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.
The input does not need to be a whole number, eg. "0.5" would cause the program to wait for half a second.
<lang lua>local socket = require("socket")
<syntaxhighlight lang="lua">local socket = require("socket")
io.write("Input a number of seconds to sleep: ")
io.write("Input a number of seconds to sleep: ")
local input = io.read("*number")
local input = io.read("*number")
print("Sleeping")
print("Sleeping")
socket.sleep(input)
socket.sleep(input)
print("Awake!")</lang>
print("Awake!")</syntaxhighlight>
A similar effect could be achieved using a "busy" loop but the function in lua-socket is gentler on your CPU.
A similar effect could be achieved using a "busy" loop but the function in lua-socket is gentler on your CPU.


=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
Statement Wait pause the current thread but other threads from module (not in this example) may run.
Statement Wait pause the current thread but other threads from module (not in this example) may run.
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module CheckIt {
Module CheckIt {
Input "Input a number of milliseconds to sleep:", N
Input "Input a number of milliseconds to sleep:", N
Line 1,595: Line 1,595:
}
}
CheckIt
CheckIt
</syntaxhighlight>
</lang>


=={{header|Maple}}==
=={{header|Maple}}==
<lang Maple>sleep := proc(secs)
<syntaxhighlight lang="maple">sleep := proc(secs)
print("Sleeping...");
print("Sleeping...");
Threads:-Sleep(secs);
Threads:-Sleep(secs);
print("Awake!");
print("Awake!");
end proc:</lang>
end proc:</syntaxhighlight>


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
This function, as you can probably guess, takes its argument in seconds.
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.
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.
<lang Mathematica>Sleep[seconds_] := (Print["Sleeping..."]; Pause[seconds]; Print["Awake!"];)</lang>
<syntaxhighlight lang="mathematica">Sleep[seconds_] := (Print["Sleeping..."]; Pause[seconds]; Print["Awake!"];)</syntaxhighlight>


=={{header|MATLAB}} / {{header|Octave}}==
=={{header|MATLAB}} / {{header|Octave}}==
<lang MATLAB>function sleep()
<syntaxhighlight lang="matlab">function sleep()


time = input('How many seconds would you like me to sleep for? ');
time = input('How many seconds would you like me to sleep for? ');
Line 1,618: Line 1,618:
disp('Awake!');
disp('Awake!');
end</lang>
end</syntaxhighlight>


=={{header|min}}==
=={{header|min}}==
{{works with|min|0.19.6}}
{{works with|min|0.19.6}}
<lang min>"Enter number of milliseconds to sleep" ask int
<syntaxhighlight lang="min">"Enter number of milliseconds to sleep" ask int
"Sleeping..." puts!
"Sleeping..." puts!
sleep
sleep
"Awake!" puts!</lang>
"Awake!" puts!</syntaxhighlight>


=={{header|Nanoquery}}==
=={{header|Nanoquery}}==
<lang nanoquery>time = int(input("time to sleep (ms): "))
<syntaxhighlight lang="nanoquery">time = int(input("time to sleep (ms): "))


println "Sleeping..."
println "Sleeping..."
sleep(time)
sleep(time)
println "Awake!"</lang>
println "Awake!"</syntaxhighlight>


=={{header|Nemerle}}==
=={{header|Nemerle}}==
<lang Nemerle>using System;
<syntaxhighlight lang="nemerle">using System;
using System.Console;
using System.Console;
using System.Threading.Thread; // this is where the Sleep() method comes from
using System.Threading.Thread; // this is where the Sleep() method comes from
Line 1,648: Line 1,648:
WriteLine("Awake!");
WriteLine("Awake!");
}
}
}</lang>
}</syntaxhighlight>


=={{header|NetRexx}}==
=={{header|NetRexx}}==
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary
options replace format comments java crossref symbols nobinary


Line 1,688: Line 1,688:
say
say
return
return
</syntaxhighlight>
</lang>


=={{header|NewLISP}}==
=={{header|NewLISP}}==
<lang NewLISP>(println "Sleeping..." )
<syntaxhighlight lang="newlisp">(println "Sleeping..." )
(sleep 2000) ; Wait for 2 seconds
(sleep 2000) ; Wait for 2 seconds
(println "Awake!")</lang>
(println "Awake!")</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
<lang Nim>import os, strutils
<syntaxhighlight lang="nim">import os, strutils


echo "Enter how long I should sleep (in milliseconds):"
echo "Enter how long I should sleep (in milliseconds):"
Line 1,702: Line 1,702:
echo "Sleeping..."
echo "Sleeping..."
sleep timed
sleep timed
echo "Awake!"</lang>
echo "Awake!"</syntaxhighlight>


=={{header|NS-HUBASIC}}==
=={{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.
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.
<lang NS-HUBASIC>10 PRINT "I'LL TELL YOU WHEN I BECOME AWAKE AGAIN..."
<syntaxhighlight lang="ns-hubasic">10 PRINT "I'LL TELL YOU WHEN I BECOME AWAKE AGAIN..."
20 PAUSE 100
20 PAUSE 100
30 PRINT "NOW I'M AWAKE AGAIN."</lang>
30 PRINT "NOW I'M AWAKE AGAIN."</syntaxhighlight>


=={{header|Objeck}}==
=={{header|Objeck}}==
<lang objeck>
<syntaxhighlight lang="objeck">
bundle Default {
bundle Default {
class Test {
class Test {
Line 1,723: Line 1,723:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|Objective-C}}==
=={{header|Objective-C}}==
Line 1,730: Line 1,730:
{{works with|GNUstep}} and {{works with|Cocoa}}
{{works with|GNUstep}} and {{works with|Cocoa}}


<lang objc>#import <Foundation/Foundation.h>
<syntaxhighlight lang="objc">#import <Foundation/Foundation.h>


int main()
int main()
Line 1,746: Line 1,746:
}
}
return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|OCaml}}==
=={{header|OCaml}}==


<lang ocaml>#load "unix.cma";;
<syntaxhighlight lang="ocaml">#load "unix.cma";;
let seconds = read_int ();;
let seconds = read_int ();;
print_endline "Sleeping...";;
print_endline "Sleeping...";;
Unix.sleep seconds;; (* number is integer in seconds *)
Unix.sleep seconds;; (* number is integer in seconds *)
print_endline "Awake!";;</lang>
print_endline "Awake!";;</syntaxhighlight>


or
or
<lang ocaml>#load "unix.cma";;
<syntaxhighlight lang="ocaml">#load "unix.cma";;
#directory "+threads";;
#directory "+threads";;
#load "threads.cma";;
#load "threads.cma";;
Line 1,763: Line 1,763:
print_endline "Sleeping...";;
print_endline "Sleeping...";;
Thread.delay seconds;; (* number is in seconds ... but accepts fractions *)
Thread.delay seconds;; (* number is in seconds ... but accepts fractions *)
print_endline "Awake!";;</lang>
print_endline "Awake!";;</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==
<lang Oforth> : sleepMilli(n) "Sleeping..." . n sleep "Awake!" println ;</lang>
<syntaxhighlight lang="oforth"> : sleepMilli(n) "Sleeping..." . n sleep "Awake!" println ;</syntaxhighlight>


=={{header|ooRexx}}==
=={{header|ooRexx}}==
<lang oorexx>Say time()
<syntaxhighlight lang="oorexx">Say time()
Call sysSleep 10 -- wait 10 seconds
Call sysSleep 10 -- wait 10 seconds
Say time()</lang>
Say time()</syntaxhighlight>
{{out}}
{{out}}
<pre>14:23:40
<pre>14:23:40
Line 1,777: Line 1,777:


=={{header|Oz}}==
=={{header|Oz}}==
<lang oz>declare
<syntaxhighlight lang="oz">declare
class TextFile from Open.file Open.text end
class TextFile from Open.file Open.text end
StdIn = {New TextFile init(name:stdin)}
StdIn = {New TextFile init(name:stdin)}
Line 1,784: Line 1,784:
{System.showInfo "Sleeping..."}
{System.showInfo "Sleeping..."}
{Delay WaitTime} %% in milliseconds
{Delay WaitTime} %% in milliseconds
{System.showInfo "Awake!"}</lang>
{System.showInfo "Awake!"}</syntaxhighlight>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
Line 1,791: Line 1,791:
===gettime===
===gettime===
The units are milliseconds.
The units are milliseconds.
<lang parigp>sleep(ms)={
<syntaxhighlight lang="parigp">sleep(ms)={
print("Sleeping...");
print("Sleeping...");
while((ms-=gettime()) > 0,);
while((ms-=gettime()) > 0,);
Line 1,797: Line 1,797:
};
};


sleep(input())</lang>
sleep(input())</syntaxhighlight>


===alarm===
===alarm===
{{works with|PARI/GP|2.4.3 and above on Linux}}
{{works with|PARI/GP|2.4.3 and above on Linux}}
The units are seconds.
The units are seconds.
<lang parigp>sleep(s)={
<syntaxhighlight lang="parigp">sleep(s)={
print("Sleeping...");
print("Sleeping...");
alarm(s);
alarm(s);
Line 1,809: Line 1,809:
};
};


sleep(input())</lang>
sleep(input())</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
Line 1,816: Line 1,816:
=={{header|Peloton}}==
=={{header|Peloton}}==
Literate mode
Literate mode
<lang sgml><@ SAYLIT>Number of seconds: </@><@ GETVAR>secs</@>
<syntaxhighlight lang="sgml"><@ SAYLIT>Number of seconds: </@><@ GETVAR>secs</@>
<@ SAYLIT>Sleeping</@>
<@ SAYLIT>Sleeping</@>
<@ ACTPAUVAR>secs</@>
<@ ACTPAUVAR>secs</@>
<@ SAYLIT>Awake</@></lang>
<@ SAYLIT>Awake</@></syntaxhighlight>


French variable-length opcodes
French variable-length opcodes
<lang sgml><# MontrezLittéralement>Number of seconds: </#><# PrenezUneValeurVariable>secs</#>
<syntaxhighlight lang="sgml"><# MontrezLittéralement>Number of seconds: </#><# PrenezUneValeurVariable>secs</#>
<# MontrezLittéralement>Sleeping</#>
<# MontrezLittéralement>Sleeping</#>
<# AgissezFaireUnePauseVariable>secs</#>
<# AgissezFaireUnePauseVariable>secs</#>
<# MontrezLittéralement>Awake</#></lang>
<# MontrezLittéralement>Awake</#></syntaxhighlight>


(Simplified) Chinese fixed-length opcodes
(Simplified) Chinese fixed-length opcodes
<lang sgml><@ 显示_字串_>Number of seconds: </@><@ 获取_变量_>secs</@>
<syntaxhighlight lang="sgml"><@ 显示_字串_>Number of seconds: </@><@ 获取_变量_>secs</@>
<@ 显示_字串_>Sleeping</@>
<@ 显示_字串_>Sleeping</@>
<@ 运行_暂停动变量_>secs</@>
<@ 运行_暂停动变量_>secs</@>
<@ 显示_字串_>Awake</@></lang>
<@ 显示_字串_>Awake</@></syntaxhighlight>


=={{header|Perl}}==
=={{header|Perl}}==


seconds:
seconds:
<lang perl>$seconds = <>;
<syntaxhighlight lang="perl">$seconds = <>;
print "Sleeping...\n";
print "Sleeping...\n";
sleep $seconds; # number is in seconds
sleep $seconds; # number is in seconds
print "Awake!\n";</lang>
print "Awake!\n";</syntaxhighlight>


microseconds and nanoseconds using the Time::HiRes module:
microseconds and nanoseconds using the Time::HiRes module:
<lang perl>use Time::HiRes qw( usleep nanosleep );
<syntaxhighlight lang="perl">use Time::HiRes qw( usleep nanosleep );


$microseconds = <>;
$microseconds = <>;
Line 1,852: Line 1,852:
print "Sleeping...\n";
print "Sleeping...\n";
nanosleep $nanoseconds;
nanosleep $nanoseconds;
print "Awake!\n";</lang>
print "Awake!\n";</syntaxhighlight>


It's also possible to sleep for fractional seconds by abusing the select function:
It's also possible to sleep for fractional seconds by abusing the select function:
<lang perl>say "Sleeping...";
<syntaxhighlight lang="perl">say "Sleeping...";
select undef, undef, undef, 0.5;
select undef, undef, undef, 0.5;
say "Awake!";</lang>
say "Awake!";</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
{{libheader|Phix/basics}}
{{libheader|Phix/basics}}
<!--<lang Phix>-->
<!--<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: #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: #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>
Line 1,867: Line 1,867:
<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;">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>
<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>
<!--</lang>-->
<!--</syntaxhighlight>-->
Note that sleep() is entirely inappropriate for GUI applications, which should instead set a routine to resume processing
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
(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
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.
that also regularly relinquishes control to the event loop, and can pick up where it left off when next invoked.
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">-- demo\rosetta\sleep.exw</span>
<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;">with</span> <span style="color: #008080;">javascript_semantics</span>
Line 1,911: Line 1,911:
<span style="color: #7060A8;">IupClose</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>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--</lang>-->
<!--</syntaxhighlight>-->


=={{header|PHP}}==
=={{header|PHP}}==


seconds:
seconds:
<lang php>$seconds = 42;
<syntaxhighlight lang="php">$seconds = 42;
echo "Sleeping...\n";
echo "Sleeping...\n";
sleep($seconds); # number is integer in seconds
sleep($seconds); # number is integer in seconds
echo "Awake!\n";</lang>
echo "Awake!\n";</syntaxhighlight>


microseconds:
microseconds:
<lang php>$microseconds = 42000000;
<syntaxhighlight lang="php">$microseconds = 42000000;
echo "Sleeping...\n";
echo "Sleeping...\n";
usleep($microseconds); # number is integer in microseconds
usleep($microseconds); # number is integer in microseconds
echo "Awake!\n";</lang>
echo "Awake!\n";</syntaxhighlight>


nanoseconds:
nanoseconds:
<lang php>$nanoseconds = 42000000000;
<syntaxhighlight lang="php">$nanoseconds = 42000000000;
echo "Sleeping...\n";
echo "Sleeping...\n";
time_nanosleep($seconds, $nanoseconds); # first arg in seconds plus second arg in nanoseconds
time_nanosleep($seconds, $nanoseconds); # first arg in seconds plus second arg in nanoseconds
echo "Awake!\n";</lang>
echo "Awake!\n";</syntaxhighlight>


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(prinl "Sleeping..." )
<syntaxhighlight lang="picolisp">(prinl "Sleeping..." )
(wait 2000) # Wait for 2 seconds
(wait 2000) # Wait for 2 seconds
(prinl "Awake!")</lang>
(prinl "Awake!")</syntaxhighlight>
As [http://software-lab.de/doc/refW.html#wait wait] will continue executing
As [http://software-lab.de/doc/refW.html#wait wait] will continue executing
background events, another possibility (for a complete stop) is calling
background events, another possibility (for a complete stop) is calling
some external program like
some external program like
<lang PicoLisp>(prinl "Sleeping..." )
<syntaxhighlight lang="picolisp">(prinl "Sleeping..." )
(call 'sleep 2) # Wait for 2 seconds
(call 'sleep 2) # Wait for 2 seconds
(prinl "Awake!")</lang>
(prinl "Awake!")</syntaxhighlight>


=={{header|Pike}}==
=={{header|Pike}}==
<lang Pike>int main() {
<syntaxhighlight lang="pike">int main() {
int seconds = (int)Stdio.stdin->gets();
int seconds = (int)Stdio.stdin->gets();
write("Sleeping...\n");
write("Sleeping...\n");
Line 1,951: Line 1,951:
write("Awake!\n");
write("Awake!\n");
return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|Pixilang}}==
=={{header|Pixilang}}==
<lang Pixilang>fputs("Sleeping...\n")
<syntaxhighlight lang="pixilang">fputs("Sleeping...\n")
sleep(1000)
sleep(1000)
fputs("Awake!\n")</lang>
fputs("Awake!\n")</syntaxhighlight>


=={{header|PL/I}}==
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
put ('sleeping');
put ('sleeping');
delay (2000); /* wait for 2 seconds (=2000 milliseconds). */
delay (2000); /* wait for 2 seconds (=2000 milliseconds). */
put ('awake');
put ('awake');
</syntaxhighlight>
</lang>


=={{header|Plain English}}==
=={{header|Plain English}}==
<lang plainenglish>To run:
<syntaxhighlight lang="plainenglish">To run:
Start up.
Start up.
Demonstrate waiting.
Demonstrate waiting.
Line 1,977: Line 1,977:
Write "Sleeping..." to the console.
Write "Sleeping..." to the console.
Wait for the milliseconds.
Wait for the milliseconds.
Write "Awake!" to the console.</lang>
Write "Awake!" to the console.</syntaxhighlight>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<lang powershell>$d = [int] (Read-Host Duration in seconds)
<syntaxhighlight lang="powershell">$d = [int] (Read-Host Duration in seconds)
Write-Host Sleeping ...
Write-Host Sleeping ...
Start-Sleep $d
Start-Sleep $d
Write-Host Awake!</lang>
Write-Host Awake!</syntaxhighlight>
The <code>-Milliseconds</code> parameter to <code>Start-Sleep</code> can be used to allow for sub-second precision in sleeping.
The <code>-Milliseconds</code> parameter to <code>Start-Sleep</code> can be used to allow for sub-second precision in sleeping.


=={{header|Prolog}}==
=={{header|Prolog}}==
Works with SWI-Prolog.
Works with SWI-Prolog.
<lang Prolog>rosetta_sleep(Time) :-
<syntaxhighlight lang="prolog">rosetta_sleep(Time) :-
writeln('Sleeping...'),
writeln('Sleeping...'),
sleep(Time),
sleep(Time),
writeln('Awake!').
writeln('Awake!').
</syntaxhighlight>
</lang>


=={{header|PureBasic}}==
=={{header|PureBasic}}==
Sleeping is performed with Delay() and a value in milliseconds. The time is accurate to approximately +/- 15 milliseconds.
Sleeping is performed with Delay() and a value in milliseconds. The time is accurate to approximately +/- 15 milliseconds.
<lang PureBasic>If OpenConsole()
<syntaxhighlight lang="purebasic">If OpenConsole()


Print("Enter a time(milliseconds) to sleep: ")
Print("Enter a time(milliseconds) to sleep: ")
Line 2,006: Line 2,006:
Input()
Input()
CloseConsole()
CloseConsole()
EndIf</lang>
EndIf</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==


<lang python>import time
<syntaxhighlight lang="python">import time


seconds = float(raw_input())
seconds = float(raw_input())
print "Sleeping..."
print "Sleeping..."
time.sleep(seconds) # number is in seconds ... but accepts fractions
time.sleep(seconds) # number is in seconds ... but accepts fractions
print "Awake!"</lang>
print "Awake!"</syntaxhighlight>


=={{header|R}}==
=={{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).
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)
sleep <- function(time=1)
{
{
Line 2,029: Line 2,029:


sleep()
sleep()
</syntaxhighlight>
</lang>


=={{header|Racket}}==
=={{header|Racket}}==
<lang racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket
(displayln "Enter a time (in seconds): ")
(displayln "Enter a time (in seconds): ")
Line 2,040: Line 2,040:
(sleep time)
(sleep time)
(displayln "Awake!"))
(displayln "Awake!"))
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
Line 2,047: Line 2,047:
The <tt>sleep</tt> function argument is in units of seconds, but these may be fractional (to the limits of your system's clock).
The <tt>sleep</tt> function argument is in units of seconds, but these may be fractional (to the limits of your system's clock).


<lang perl6>my $sec = prompt("Sleep for how many microfortnights? ") * 1.2096;
<syntaxhighlight lang="raku" line>my $sec = prompt("Sleep for how many microfortnights? ") * 1.2096;
say "Sleeping...";
say "Sleeping...";
sleep $sec;
sleep $sec;
say "Awake!";</lang>
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.
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}}==
=={{header|RapidQ}}==
<syntaxhighlight lang="vb">
<lang vb>
input "Enter the number of seconds to sleep: ";s
input "Enter the number of seconds to sleep: ";s
sleep s
sleep s
print "I'm awake I think..."
print "I'm awake I think..."
input "Press enter to quit";a$
input "Press enter to quit";a$
</syntaxhighlight>
</lang>


=={{header|REBOL}}==
=={{header|REBOL}}==
<lang REBOL>REBOL [
<syntaxhighlight lang="rebol">REBOL [
Title: "Sleep Main Thread"
Title: "Sleep Main Thread"
URL: http://rosettacode.org/wiki/Sleep_the_Main_Thread
URL: http://rosettacode.org/wiki/Sleep_the_Main_Thread
Line 2,071: Line 2,071:
print "Sleeping..."
print "Sleeping..."
wait naptime
wait naptime
print "Awake!"</lang>
print "Awake!"</syntaxhighlight>


=={{header|Red}}==
=={{header|Red}}==
<syntaxhighlight lang="red">
<lang Red>
str-time: to integer! ask "Enter wait time " ;get user input , convert to integer
str-time: to integer! ask "Enter wait time " ;get user input , convert to integer
print "waiting"
print "waiting"
wait str-time ;Seconds
wait str-time ;Seconds
print "awake"</lang>
print "awake"</syntaxhighlight>


=={{header|Retro}}==
=={{header|Retro}}==
Retro has no fine grained timer; so we have to make due with seconds.
Retro has no fine grained timer; so we have to make due with seconds.


<lang Retro>: sleep ( n- )
<syntaxhighlight lang="retro">: sleep ( n- )
[ time [ time over - 1 > ] until drop ] times ;
[ time [ time over - 1 > ] until drop ] times ;
: test
: test
"\nTime to sleep (in seconds): " puts getToken toNumber
"\nTime to sleep (in seconds): " puts getToken toNumber
"\nSleeping..." sleep
"\nSleeping..." sleep
"\nAwake!\n" ;</lang>
"\nAwake!\n" ;</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
Line 2,097: Line 2,097:


Note: &nbsp; the above two REXX interpreters support fractional seconds.
Note: &nbsp; the above two REXX interpreters support fractional seconds.
<lang rexx>/*REXX program sleeps X seconds (the number of seconds is supplied via the argument).*/
<syntaxhighlight lang="rexx">/*REXX program sleeps X seconds (the number of seconds is supplied via the argument).*/
parse arg secs . /*obtain optional argument from the CL.*/
parse arg secs . /*obtain optional argument from the CL.*/
if secs=='' | secs=="," then secs=0 /*Not specified? Then assume 0 (zero).*/
if secs=='' | secs=="," then secs=0 /*Not specified? Then assume 0 (zero).*/
Line 2,103: Line 2,103:
call delay secs /*Snooze. Hopefully, just a short nap.*/
call delay secs /*Snooze. Hopefully, just a short nap.*/
say 'Awake!' /*and now inform invoker we're running.*/
say 'Awake!' /*and now inform invoker we're running.*/
/*stick a fork in it, we're all done. */</lang>
/*stick a fork in it, we're all done. */</syntaxhighlight>
'''output''' &nbsp; when using the following for input: &nbsp; <tt> 4.7 </tt>
'''output''' &nbsp; when using the following for input: &nbsp; <tt> 4.7 </tt>
<pre>
<pre>
Line 2,127: Line 2,127:


This REXX program only uses whole seconds &nbsp; (fractional seconds are ignored).
This REXX program only uses whole seconds &nbsp; (fractional seconds are ignored).
<lang rexx>/*REXX program delays (or SLEEPS) a number of whole seconds; fractional secs 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. */
trace off /*suppress REXX error messages. */
parse arg ! /*obtain all the arguments. */
parse arg ! /*obtain all the arguments. */
Line 2,179: Line 2,179:
isNum: return datatype(arg(1), 'N')
isNum: return datatype(arg(1), 'N')
noValue: !sigl=sigl; call er 17, !fid(2) !fid(3) !sigl condition('D') sourceline(!sigl)
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)</lang>
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.
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.


Line 2,187: Line 2,187:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
load "guilib.ring"
load "guilib.ring"


Line 2,200: Line 2,200:
oTest = new qTest
oTest = new qTest
oTest.qsleep(nTime)
oTest.qsleep(nTime)
</syntaxhighlight>
</lang>


Output:
Output:
Line 2,209: Line 2,209:


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>seconds = gets.to_f
<syntaxhighlight lang="ruby">seconds = gets.to_f
puts "Sleeping..."
puts "Sleeping..."
sleep(seconds) # number is in seconds ... but accepts fractions
sleep(seconds) # number is in seconds ... but accepts fractions
# Minimum resolution is system dependent.
# Minimum resolution is system dependent.
puts "Awake!"</lang>
puts "Awake!"</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==
<lang rust>use std::{io, time, thread};
<syntaxhighlight lang="rust">use std::{io, time, thread};


fn main() {
fn main() {
Line 2,234: Line 2,234:
thread::sleep(sleep_duration);
thread::sleep(sleep_duration);
println!("Awake!");
println!("Awake!");
}</lang>
}</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
{{libheader|Scala}}<lang scala>object Sleeper extends App {
{{libheader|Scala}}<syntaxhighlight lang="scala">object Sleeper extends App {
print("Enter sleep time in milli sec: ")
print("Enter sleep time in milli sec: ")
val ms = scala.io.StdIn.readInt()
val ms = scala.io.StdIn.readInt()
Line 2,244: Line 2,244:
Thread.sleep(ms)
Thread.sleep(ms)
println(s"Awaked after [${scala.compat.Platform.currentTime - sleepStarted} ms]1")
println(s"Awaked after [${scala.compat.Platform.currentTime - sleepStarted} ms]1")
}</lang>
}</syntaxhighlight>


=={{header|Scheme}}==
=={{header|Scheme}}==
Line 2,251: Line 2,251:
The following works in Chicken Scheme:
The following works in Chicken Scheme:


<lang scheme>
<syntaxhighlight lang="scheme">
(use format)
(use format)
(use srfi-18)
(use srfi-18)
Line 2,263: Line 2,263:
(format #t "Awake!~&"))
(format #t "Awake!~&"))
(format #t "You must enter a number~&")))
(format #t "You must enter a number~&")))
</syntaxhighlight>
</lang>


Scheme implementations also provide alternative approaches. For example, Chicken Scheme has a 'posix' library which includes a 'sleep' function.
Scheme implementations also provide alternative approaches. For example, Chicken Scheme has a 'posix' library which includes a 'sleep' function.
Line 2,271: Line 2,271:
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.
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.


<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "duration.s7i";
include "duration.s7i";


Line 2,283: Line 2,283:
wait(secondsToSleep . SECONDS);
wait(secondsToSleep . SECONDS);
writeln("Awake!");
writeln("Awake!");
end func;</lang>
end func;</syntaxhighlight>


=={{header|SenseTalk}}==
=={{header|SenseTalk}}==
SenseTalk understands time durations expressed in any units, including: seconds, minutes, days, microseconds, shakes, and jiffies!
SenseTalk understands time durations expressed in any units, including: seconds, minutes, days, microseconds, shakes, and jiffies!
<lang sensetalk>
<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!"
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
get the value of it
Line 2,302: Line 2,302:
put "Awake!"
put "Awake!"


</syntaxhighlight>
</lang>


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>var sec = read(Number); # any positive number (it may be fractional)
<syntaxhighlight lang="ruby">var sec = read(Number); # any positive number (it may be fractional)
say "Sleeping...";
say "Sleeping...";
Sys.sleep(sec); # in seconds
Sys.sleep(sec); # in seconds
#Sys.usleep(sec); # in microseconds
#Sys.usleep(sec); # in microseconds
#Sys.nanosleep(sec); # in nanoseconds
#Sys.nanosleep(sec); # in nanoseconds
say "Awake!";</lang>
say "Awake!";</syntaxhighlight>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
{{works with|Pharo}}
{{works with|Pharo}}
<lang smalltalk>t := (FillInTheBlankMorph request: 'Enter time in seconds') asNumber.
<syntaxhighlight lang="smalltalk">t := (FillInTheBlankMorph request: 'Enter time in seconds') asNumber.
Transcript show: 'Sleeping...'.
Transcript show: 'Sleeping...'.
(Delay forSeconds: t) wait.
(Delay forSeconds: t) wait.
Transcript show: 'Awake!'.
Transcript show: 'Awake!'.
</syntaxhighlight>
</lang>
{{works with|Smalltalk/X}}
{{works with|Smalltalk/X}}
<lang smalltalk>t := (Dialog request: 'Enter time in seconds') asNumber.
<syntaxhighlight lang="smalltalk">t := (Dialog request: 'Enter time in seconds') asNumber.
Transcript show: 'Sleeping...'.
Transcript show: 'Sleeping...'.
(Delay forSeconds: t) wait.
(Delay forSeconds: t) wait.
Transcript show: 'Awake!'.
Transcript show: 'Awake!'.
</syntaxhighlight>
</lang>
(of course, you can "Smalltalk at:#FillInTheBlankMorph put:Dialog", to be source compatible with Pharo)
(of course, you can "Smalltalk at:#FillInTheBlankMorph put:Dialog", to be source compatible with Pharo)


=={{header|Standard ML}}==
=={{header|Standard ML}}==
<lang ocaml>(TextIO.print "input a number of seconds please: ";
<syntaxhighlight lang="ocaml">(TextIO.print "input a number of seconds please: ";
let val seconds = valOf (Int.fromString (valOf (TextIO.inputLine TextIO.stdIn))) in
let val seconds = valOf (Int.fromString (valOf (TextIO.inputLine TextIO.stdIn))) in
TextIO.print "Sleeping...\n";
TextIO.print "Sleeping...\n";
Line 2,335: Line 2,335:
I dunno why; it doesn't say anything about this in the documentation *)
I dunno why; it doesn't say anything about this in the documentation *)
TextIO.print "Awake!\n"
TextIO.print "Awake!\n"
end)</lang>
end)</syntaxhighlight>


=={{header|Stata}}==
=={{header|Stata}}==
<lang stata>program sleep_awake
<syntaxhighlight lang="stata">program sleep_awake
* pass duration in milliseconds
* pass duration in milliseconds
display "Sleeping..."
display "Sleeping..."
Line 2,345: Line 2,345:
end
end


sleep_awake 2000</lang>
sleep_awake 2000</syntaxhighlight>


=={{header|Suneido}}==
=={{header|Suneido}}==
<lang Suneido>function (time)
<syntaxhighlight lang="suneido">function (time)
{
{
Print("Sleeping...")
Print("Sleeping...")
Sleep(time) // time is in milliseconds
Sleep(time) // time is in milliseconds
Print("Awake!")
Print("Awake!")
}</lang>
}</syntaxhighlight>


=={{header|Swift}}==
=={{header|Swift}}==
<lang Swift>import Foundation
<syntaxhighlight lang="swift">import Foundation


println("Enter number of seconds to sleep")
println("Enter number of seconds to sleep")
Line 2,365: Line 2,365:
NSThread.sleepForTimeInterval(interval)
NSThread.sleepForTimeInterval(interval)


println("Awake!")</lang>
println("Awake!")</syntaxhighlight>


=={{header|Tcl}}==
=={{header|Tcl}}==
Blocking example (the process is blocked preventing any background activity).
Blocking example (the process is blocked preventing any background activity).
<lang tcl>puts -nonewline "Enter a number of milliseconds to sleep: "
<syntaxhighlight lang="tcl">puts -nonewline "Enter a number of milliseconds to sleep: "
flush stdout
flush stdout
set millis [gets stdin]
set millis [gets stdin]
puts Sleeping...
puts Sleeping...
after $millis
after $millis
puts Awake!</lang>
puts Awake!</syntaxhighlight>


A non-blocking example where background activity will occur.
A non-blocking example where background activity will occur.
<lang tcl>puts -nonewline "Enter a number of milliseconds to sleep: "
<syntaxhighlight lang="tcl">puts -nonewline "Enter a number of milliseconds to sleep: "
flush stdout
flush stdout
set millis [gets stdin]
set millis [gets stdin]
Line 2,384: Line 2,384:
after $millis set ::wakeupflag 1
after $millis set ::wakeupflag 1
vwait ::wakeupflag
vwait ::wakeupflag
puts Awake!</lang>
puts Awake!</syntaxhighlight>


=={{header|TI-89 BASIC}}==
=={{header|TI-89 BASIC}}==
Line 2,415: Line 2,415:


=={{header|TUSCRIPT}}==
=={{header|TUSCRIPT}}==
<lang tuscript>
<syntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
$$ MODE TUSCRIPT
secondsrange=2
secondsrange=2
Line 2,421: Line 2,421:
WAIT #secondsrange
WAIT #secondsrange
PRINT "Awake after Naping ",secondsrange, " seconds"
PRINT "Awake after Naping ",secondsrange, " seconds"
</syntaxhighlight>
</lang>


=={{header|TXR}}==
=={{header|TXR}}==


<lang txrlisp>(let ((usec (progn (put-string "enter sleep usecs: ")
<syntaxhighlight lang="txrlisp">(let ((usec (progn (put-string "enter sleep usecs: ")
(tointz (get-line)))))
(tointz (get-line)))))
(put-string "Sleeping ... ")
(put-string "Sleeping ... ")
(flush-stream)
(flush-stream)
(usleep usec)
(usleep usec)
(put-line "Awake!"))</lang>
(put-line "Awake!"))</syntaxhighlight>


=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
<lang bash>printf "Enter a time in seconds to sleep: "
<syntaxhighlight lang="bash">printf "Enter a time in seconds to sleep: "
read seconds
read seconds
echo "Sleeping..."
echo "Sleeping..."
sleep "$seconds"
sleep "$seconds"
echo "Awake!"</lang>
echo "Awake!"</syntaxhighlight>


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>.
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}}==
=={{header|Ursa}}==
<lang ursa>out "Sleeping..." endl console
<syntaxhighlight lang="ursa">out "Sleeping..." endl console
# sleep for 5 seconds (5000 milliseconds)
# sleep for 5 seconds (5000 milliseconds)
sleep 5000
sleep 5000
out "Awake!" endl console</lang>
out "Awake!" endl console</syntaxhighlight>


=={{header|VBA}}==
=={{header|VBA}}==
<syntaxhighlight lang="vba">
<lang VBA>
Function Sleep(iSecsWait As Integer)
Function Sleep(iSecsWait As Integer)
Debug.Print Now(), "Sleeping..."
Debug.Print Now(), "Sleeping..."
Line 2,454: Line 2,454:
Debug.Print Now(), "Awake!"
Debug.Print Now(), "Awake!"
End Function
End Function
</syntaxhighlight>
</lang>


=={{header|VBScript}}==
=={{header|VBScript}}==
<syntaxhighlight lang="vbscript">
<lang VBScript>
iSeconds=InputBox("Enter a time in seconds to sleep: ","Sleep Example for RosettaCode.org")
iSeconds=InputBox("Enter a time in seconds to sleep: ","Sleep Example for RosettaCode.org")
WScript.Echo "Sleeping..."
WScript.Echo "Sleeping..."
WScript.Sleep iSeconds*1000 'Sleep is done in Milli-Seconds
WScript.Sleep iSeconds*1000 'Sleep is done in Milli-Seconds
WScript.Echo "Awake!"
WScript.Echo "Awake!"
</syntaxhighlight>
</lang>


<!--Out of alphabetical order to keep the VB languages together-->
<!--Out of alphabetical order to keep the VB languages together-->


=={{header|Vedit macro language}}==
=={{header|Vedit macro language}}==
<lang vedit>#1 = Get_Num("Sleep time in 1/10 seconds: ")
<syntaxhighlight lang="vedit">#1 = Get_Num("Sleep time in 1/10 seconds: ")
Message("Sleeping...\n")
Message("Sleeping...\n")
Sleep(#1)
Sleep(#1)
Message("Awake!\n")</lang>
Message("Awake!\n")</syntaxhighlight>


=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==


<lang vbnet>Module Program
<syntaxhighlight lang="vbnet">Module Program
Sub Main()
Sub Main()
Dim millisecondsSleepTime = Integer.Parse(Console.ReadLine(), Globalization.CultureInfo.CurrentCulture)
Dim millisecondsSleepTime = Integer.Parse(Console.ReadLine(), Globalization.CultureInfo.CurrentCulture)
Line 2,481: Line 2,481:
Console.WriteLine("Awake!")
Console.WriteLine("Awake!")
End Sub
End Sub
End Module</lang>
End Module</syntaxhighlight>


=={{header|Vlang}}==
=={{header|Vlang}}==
<lang>import time
<syntaxhighlight lang="text">import time
import os
import os


Line 2,492: Line 2,492:
time.sleep(time.Duration(sec * time.second))
time.sleep(time.Duration(sec * time.second))
println("Awake!")
println("Awake!")
}</lang>
}</syntaxhighlight>


=={{header|Wren}}==
=={{header|Wren}}==
<lang ecmascript>import "timer" for Timer
<syntaxhighlight lang="ecmascript">import "timer" for Timer
import "io" for Stdin, Stdout
import "io" for Stdin, Stdout


Line 2,509: Line 2,509:
System.print("Sleeping...")
System.print("Sleeping...")
Timer.sleep((secs*1000).floor)
Timer.sleep((secs*1000).floor)
System.print("Awake!")</lang>
System.print("Awake!")</syntaxhighlight>


{{out}}
{{out}}
Line 2,521: Line 2,521:
=={{header|X86 Assembly}}==
=={{header|X86 Assembly}}==
==={{header|NASM 2.15}}===
==={{header|NASM 2.15}}===
<lang asm>
<syntaxhighlight lang="asm">
%macro sysdef 2
%macro sysdef 2
%define sys_%1 %2
%define sys_%1 %2
Line 2,564: Line 2,564:
inv exit, 0
inv exit, 0
ret
ret
</syntaxhighlight>
</lang>




Line 2,570: Line 2,570:
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.
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.


<lang x86asm>
<syntaxhighlight lang="x86asm">
; x86_64 linux nasm
; x86_64 linux nasm


Line 2,585: Line 2,585:
add rsp, 16 ; clean up stack
add rsp, 16 ; clean up stack
ret
ret
</syntaxhighlight>
</lang>


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>int Microseconds;
<syntaxhighlight lang="xpl0">int Microseconds;
[Microseconds:= IntIn(0);
[Microseconds:= IntIn(0);
Text(0, "Sleeping...^m^j");
Text(0, "Sleeping...^m^j");
DelayUS(Microseconds);
DelayUS(Microseconds);
Text(0, "Awake!^m^j");
Text(0, "Awake!^m^j");
]</lang>
]</syntaxhighlight>


=={{header|zig}}==
=={{header|zig}}==
<lang zig>const std = @import("std");
<syntaxhighlight lang="zig">const std = @import("std");
const time = std.time;
const time = std.time;
const warn = std.debug.warn;
const warn = std.debug.warn;
Line 2,606: Line 2,606:


warn("Awake!\n");
warn("Awake!\n");
}</lang>
}</syntaxhighlight>


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>seconds:=ask("Seconds to sleep: ").toFloat();
<syntaxhighlight lang="zkl">seconds:=ask("Seconds to sleep: ").toFloat();
println("Sleeping...");
println("Sleeping...");
Atomic.sleep(seconds); # float, usually millisecond resolution
Atomic.sleep(seconds); # float, usually millisecond resolution
println("Awake!");</lang>
println("Awake!");</syntaxhighlight>


=={{header|Zoomscript}}==
=={{header|Zoomscript}}==
For typing:
For typing:
<lang Zoomscript>print "Sleeping..."
<syntaxhighlight lang="zoomscript">print "Sleeping..."
wait 1
wait 1
println
println
print "Awake!"</lang>
print "Awake!"</syntaxhighlight>
For importing:
For importing: