Sleep

From Rosetta Code
Jump to: navigation, search
Task
Sleep
You are encouraged to solve this task according to the task description, using any language you may know.

Write a program that does the following in this order:

  • Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description.
  • Print "Sleeping..."
  • Sleep the main thread for the given amount of time.
  • Print "Awake!"
  • End.
Cf.

Contents

[edit] 360 Assembly

REENTRANT means the program can be called from several callers simultanously. The program obtains storage (memory) at each invocation. Sleep (logically swapped out task) is established through STIMER macro (SVC 47)

 
START
PRINT DATA,GEN
YREGS , REGISTER EQUATES (e.g. 0 = R0)
SLEEP CSECT
SLEEP AMODE 31 addressing mode 31 bit
SLEEP RMODE ANY loader determines 31 or 24
***********************************************************************
* REENTRANT. Logically swap out a task for a number of seconds
* specified in PARM. Minimum 0, maximum 60 seconds
*
* MVS rexx (the original rexx) does not have a sleep function. This
* program can be called from rexx, assuming this program is in
* LINKLIST, as follows:
*
* /* rexx */
* wait_time = '6' /* number of seconds to sleep */
* say 'Sleeping...'
* address LINKMVS "SLEEP wait_time" /* invoke SLEEP */
* say 'Awake!
***********************************************************************
PROLOG BAKR R14,0 satck caller's registers
LR R4,R1 save parm pointer
LR R12,R15 entry point addr to R12
USING SLEEP,R12 tell assembler about that
B AROUND avoid abend S0C1
DC C'SLEEP ' CSECT NAME
DC C'C=2014.05.10 ' CHANGE DATE
DC C'A=&SYSDATE ' ASSEMBLY DATE
DC C'T=&SYSTIME ' CHANGE TIME
DC C'MarcvdM. ' PROGRAMMER NAME
AROUND L R10,0(0,R4) load parm address in R10
XR R15,R15 clear R15
LH R15,0(0,R10) load parm length in R15
LR R6,R15 save length in R6
LTR R15,R15 parm length 0?
BZ NOPARM yes, exit before getmain
C R6,F2 parmlength > 2 ?
BH NOPARM yes, exit before getmain
STORAGE OBTAIN,LENGTH=WALEN,LOC=ANY get some storage
LR R9,R1 address of storage in R9
USING WAREAX,R9 base for data section (DSECT)
MVC EYECAT,=C'**MARC**' make storage easy to find in dump
MVC SECONDS,C00 set field to F0F0
C R6,F1 parmlength = 1?
BNE COPYSECS no, copy both bytes
MVC SECONDS+1(1),2(R10) yes, just copy one byte.
B TRTEST
COPYSECS MVC SECONDS,2(R10)
* test supplied parameter for valid integer values
TRTEST TRT SECONDS(1),VALINT6 first parm byte no higher as 6?
BNZ NOPARM_REL higher, release storage and return
TRT SECONDS+1(1),VALINT9 second byte valid?
BNZ NOPARM_REL no, release storage and return
CLC SECONDS(1),=C'6' first parm byte < 6?
BNE DOWAIT yes, do wait
CLC SECONDS+1(1),=C'0' first eq. 6, second > 0?
BNE NOPARM_REL yes, release storage and return
DOWAIT DS 0H
MVC WAWTO(DWTOL),DWTO copy WTO list form to obtained st.
MVC WAWTO+18(2),SECONDS copy in nr. of seconds
WTO MF=(E,WAWTO) issue WTO, execute form
MVC HOURS,C00 zero out hours
MVC MINUTS,C00 and minutes
MVC REST,C00 and milliseconds
STIMER WAIT,DINTVL=TIMEVAL SVC 47: logical swap out (sleep)
B EXIT done
NOPARM_REL DS 0H
STORAGE RELEASE,ADDR=(R9),LENGTH=WALEN free obtained storage
LA R15,4 set return code 4
B RETURN return to caller
EXIT DS 0H
STORAGE RELEASE,ADDR=(R9),LENGTH=WALEN free obtained storage
WTO ' Awake!',ROUTCDE=11 fixed wake-up string
NOPARM EQU *
RETURN PR , return to caller
*
* --------------------------------------------------------------------
* CONSTANTS
* --------------------------------------------------------------------
DWTO WTO ' Sleeping... (XX seconds)',ROUTCDE=11,MF=L
DWTOL EQU *-DWTO length of WTO list form
F1 DC F'1'
F2 DC F'2'
C00 DC C'00'
VALINT6 DC 256XL1'01'
ORG *-16
VALOK6 DC 7XL1'00' F0-F6: OFFSETS 240-246
VALINT9 DC 256XL1'01'
ORG *-16
VALOK9 DC 10XL1'00' F0-F9: OFFSETS 240-249
DS 0D
LTORG , FORCE DISPLACEMENT LITERALS
* --------------------------------------------------------------------
* DSECT (data section)
* --------------------------------------------------------------------
WAREAX DSECT ,
WAWTO DS CL(DWTOL) reentrant WTO area
EYECAT DS CL8
TIMEVAL DS 0CL8
HOURS DS CL2 will be zeroed
MINUTS DS CL2 will be zeroed
SECONDS DS CL2 from parm
REST DS CL2 will be zeroed
WALEN EQU *-WAREAX length of DSECT
* --------------------------------------------------------------------
END SLEEP
 

output invoked with PARM='6' (+ sign indicates "problem state" (non system key) execution

+ Sleeping... (06 seconds)  
+ Awake!                    

[edit] Ada

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.Text_Io; use Ada.Text_Io;
with Ada.Float_Text_Io; use Ada.Float_Text_Io;
 
procedure Sleep is
In_Val : Float;
begin
Get(In_Val);
Put_Line("Sleeping...");
delay Duration(In_Val);
Put_Line("Awake!");
end Sleep;

[edit] Aime

o_text("Sleeping...\n");
 
# Sleep X seconds
sleep(atoi(argv(1)));
 
# Sleep X microseconds
#usleep(atoi(argv(1)));
 
o_text("Awake!\n");

[edit] AutoHotkey

TrayTip, sleeping, sleeping
sleep, 2000 ; 2 seconds
TrayTip, awake, awake
Msgbox, awake

[edit] AutoIt

#AutoIt Version: 3.2.10.0
$sleep_me=InputBox("Sleep", "Number of seconds to sleep", "10", "", -1, -1, 0, 0)
Dim $sleep_millisec=$sleep_me*1000
MsgBox(0,"Sleep","Sleeping for "&$sleep_me&" sec")
sleep ($sleep_millisec)
MsgBox(0,"Awake","... Awaking")

[edit] AWK

 
# syntax: GAWK -f SLEEP.AWK [seconds]
BEGIN {
print("Sleeping...")
loop(ARGV[1])
print("Awake!")
exit(0)
}
function loop(seconds, t) {
# awk lacks a sleep mechanism, so simulate one by looping
t = systime()
while (systime() < t + seconds) {}
}
 

commands and output:

GAWK "BEGIN{print(strftime())}"
GAWK -f SLEEP.AWK 3
GAWK "BEGIN{print(strftime())}"

Wed Jan 16 18:06:44 Eastern Standard Time 2013
Sleeping...
Awake!
Wed Jan 16 18:06:47 Eastern Standard Time 2013

[edit] BASIC

Works with: QuickBasic version 4.5
INPUT sec 'the SLEEP command takes seconds
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.

[edit] ZX Spectrum Basic

Pressing a key will cut the pause short on the ZX Spectrum.

10 REM s is the number of seconds
20 LET s = 5
30 PRINT "Sleeping"
40 PAUSE s * 50
50 PRINT "Awake"

[edit] Batch File

The usual way to do this is to use the ping utility which waits a second between multiple tries. To wait n seconds one tells ping to make n + 1 tries and redirects the output:

Works with: Windows NT version 4
@echo off
set /p Seconds=Enter the number of seconds to sleep:
set /a Seconds+=1
echo Sleeping ...
ping -n %Seconds% localhost >nul 2>&1
echo Awake!

A similar trick can be used to wait a certain number of milliseconds. The ping utility includes a /w 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
@echo off
set /p MilliSeconds=Enter the number of milliseconds to sleep:
echo Sleeping ...
ping -n 1 -w %MilliSeconds% 1.2.3.4 >nul 2>&1
echo Awake!

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

Works with: Windows Vista
@echo off
set /p Seconds=Enter the number of seconds to sleep:
echo Sleeping ...
timeout /t %Seconds% /nobreak >nul
echo Awake!

[edit] BBC BASIC

      INPUT "Enter the time to sleep in centiseconds: " sleep%
PRINT "Sleeping..."
WAIT sleep%
PRINT "Awake!"

Whilst sleeping BBC BASIC for Windows periodically tests for the ESCape key being pressed.

[edit] C

Works with: POSIX

The function sleep needs seconds, which are read from the standard input.

#include <stdio.h>
#include <unistd.h>
 
int main()
{
unsigned int seconds;
scanf("%u", &seconds);
printf("Sleeping...\n");
sleep(seconds);
printf("Awake!\n");
return 0;
}

[edit] C++

Works with: C++11
#include <iostream>
#include <thread>
#include <chrono>
int main()
{
unsigned long microseconds;
std::cin >> microseconds;
std::cout << "Sleeping..." << std::endl;
std::this_thread::sleep_for(std::chrono::microseconds(microseconds));
std::cout << "Awake!\n";
}
 
Works with: POSIX
#include <unistd.h>
#include <iostream>
 
using namespace std;
 
int main(int argc, char* argv[])
{
useconds_t microseconds;
cin >> microseconds;
cout << "Sleeping..." << endl;
usleep(microseconds);
cout << "Awake!" << endl;
return 0;
}

[edit] C#

using System;
using System.Threading;
 
class Program
{
static void Main(string[] args)
{
int sleep = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Sleeping...");
Thread.Sleep(sleep); //milliseconds
Console.WriteLine("Awake!");
}
}


[edit] Clojure

(defn sleep [ms] ; time in milliseconds
(println "Sleeping...")
(Thread/sleep ms)
(println "Awake!"))
; call it
(sleep 1000)

[edit] COBOL

There are two methods for putting the program to sleep, both requiring unofficial extensions. The first expects the amount of time to be in seconds.

Works with: ACUCOBOL-GT
Works with: OpenCOBOL
       IDENTIFICATION DIVISION.
PROGRAM-ID. Sleep-In-Seconds.
 
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Seconds-To-Sleep USAGE COMP-2.
 
PROCEDURE DIVISION.
ACCEPT Seconds-To-Sleep
 
DISPLAY "Sleeping..."
 
CALL "C$SLEEP" USING BY CONTENT Seconds-To-Sleep
 
DISPLAY "Awake!"
 
GOBACK
.

While the second expects the time to be in nanoseconds. Note: Windows systems can only sleep to the nearest millisecond.

Works with: OpenCOBOL
       IDENTIFICATION DIVISION.
PROGRAM-ID. Sleep-In-Nanoseconds.
 
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Seconds-To-Sleep USAGE COMP-2.
01 Nanoseconds-To-Sleep USAGE COMP-2.
01 Nanoseconds-Per-Second CONSTANT 1000000000.
 
PROCEDURE DIVISION.
ACCEPT Seconds-To-Sleep
MULTIPLY Seconds-To-Sleep BY Nanoseconds-Per-Second
GIVING Nanoseconds-To-Sleep
 
DISPLAY "Sleeping..."
 
CALL "CBL_OC_NANOSLEEP"
USING BY CONTENT Nanoseconds-To-Sleep
 
DISPLAY "Awake!"
 
GOBACK
.

[edit] Common Lisp

(defun test-sleep ()
(let ((seconds (read)))
(format t "Sleeping...~%")
(sleep seconds)
(format t "Awake!~%")))
 
(test-sleep)

[edit] D

import std.stdio, core.thread;
 
void main() {
write("Enter a time to sleep (in seconds): ");
 
long secs;
readf(" %d", &secs);
 
writeln("Sleeping...");
Thread.sleep(dur!"seconds"(secs));
writeln("Awake!");
}
Output:
Enter a time to sleep (in seconds): 5
Sleeping...
Awake!

[edit] Delphi

program SleepOneSecond;
 
{$APPTYPE CONSOLE}
 
uses SysUtils;
 
var
lTimeToSleep: Integer;
begin
if ParamCount = 0 then
lTimeToSleep := 1000
else
lTimeToSleep := StrToInt(ParamStr(1));
WriteLn('Sleeping...');
Sleep(lTimeToSleep); // milliseconds
WriteLn('Awake!');
end.

[edit] E

You can't do that.

No, really. E's approach to timing, concurrency, and IO is non-blocking; if you want to wait for something, you say what you want to do when it happens — i.e. callbacks. There are no threads of control which can be stopped — except automatically when they just have nothing to do.

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.

def sleep(milliseconds :int, nextThing) {
stdout.println("Sleeping...")
timer.whenPast(timer.now() + milliseconds, fn {
stdout.println("Awake!")
nextThing()
})
}

[edit] EGL

program Sleep type BasicProgram{}
 
// Syntax: sysLib.wait(time BIN(9,2) in)
 
function main()
SysLib.writeStdout("Sleeping!");
sysLib.wait(15); // waits for 15 seconds
SysLib.writeStdout("Awake!");
end
 
end

[edit] Eiffel

The feature sleep is defined in the library class EXECUTION_ENVIRONMENT. So the demonstration class APPLICATION inherits from EXECUTION_ENVIRONMENT in order to make sleep available.

sleep takes an argument which declares the number of nanoseconds to suspend the thread's execution.

class
APPLICATION
inherit
EXECUTION_ENVIRONMENT
create
make
feature -- Initialization
make
-- Sleep for a given number of nanoseconds.
do
print ("Enter a number of nanoseconds: ")
io.read_integer_64
print ("Sleeping...%N")
sleep (io.last_integer_64)
print ("Awake!%N")
end
end

Output (sleeping 10 seconds):

Enter a number of nanoseconds: 10000000000
Sleeping...
Awake!

[edit] Emacs Lisp

(let ((seconds (read-number "Time in seconds: ")))
(message "Sleeping ...")
(sleep-for seconds)
(message "Awake!"))

The time can be a decimal like 1.5 though the actual resolution of sleep-for depends on the operating system. The similar sit-for stops sleeping if there's pending keyboard input.

read-number is new in Emacs 22 and XEmacs 21. In earlier versions similar can be had with

(string-to-number (read-string "Time in seconds: "))

This returns 0 on a non-number whereas read-number re-prompts (except in Emacs 24.3 where a bug caused read-number to return 0 :-( ).

[edit] Erlang

Erlang doesn't really have such a thing as a main thread. However, sleeping any process can be done with the timer:sleep/1 function:

main() ->
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 receive, so you may sometimes encounter the following way of sleeping a process:

main() ->
io:format("Sleeping...~n"),
receive
after 1000 -> ok %% in milliseconds
end,
io:format("Awake!~n").

which is the way it is implemented in the timer module.

[edit] F#

Translation of: C#
open System
open System.Threading
 
[<EntryPoint>]
let main args =
let sleep = Convert.ToInt32(Console.ReadLine())
Console.WriteLine("Sleeping...")
Thread.Sleep(sleep); //milliseconds
Console.WriteLine("Awake!")
0

[edit] Factor

USING: calendar io math.parser threads ;
 
: read-sleep ( -- )
readln string>number seconds
"Sleeping..." print
sleep
"Awake!" print ;

[edit] Fantom

Fantom has a 'Duration' class, which uses time definitions with units: e.g., 5sec, 100ns, 5hr. These are used for input in the following program.

 
using concurrent
 
class Main
{
public static Void main ()
{
echo ("Enter a time to sleep: ")
input := Env.cur.in.readLine
try
{
time := Duration.fromStr (input)
echo ("sleeping ...")
Actor.sleep (time)
echo ("awake!")
}
catch
{
echo ("Invalid time entered")
}
}
}
 

Output:

Enter a time to sleep: 
5sec
sleeping ...
awake!

[edit] FBSL

#APPTYPE CONSOLE
DIM %msec
PRINT "Milliseconds to sleep: ";
%msec = FILEGETS(stdin, 10)
PRINT "Sleeping..."
SLEEP(%msec)
PRINT "Awake!"
PAUSE
 

Output

Milliseconds to sleep: 1000
Sleeping...
Awake!

Press any key to continue...

[edit] Forth

: sleep ( ms -- )
." Sleeping..."
ms
." awake." cr ;

[edit] Fortran

program test_sleep
 
implicit none
integer :: iostat
integer :: seconds
character (32) :: argument
 
if (iargc () == 1) then
call getarg (1, argument)
read (argument, *, iostat = iostat) seconds
if (iostat == 0) then
write (*, '(a)') 'Sleeping...'
call sleep (seconds)
write (*, '(a)') 'Awake!'
end if
end if
 
end program test_sleep

[edit] 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"]]
while ! (t conforms time)
 
println["Sleeping..."]
sleep[t]
println["Awake!"]
 

[edit] 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.

package main
 
import "time"
import "fmt"
 
func main() {
fmt.Print("Enter number of seconds to sleep: ")
var sec float64
fmt.Scanf("%f", &sec)
fmt.Print("Sleeping…")
time.Sleep(time.Duration(sec * float64(time.Second)))
fmt.Println("\nAwake!")
}

[edit] Groovy

Solution:

def sleepTest = {
println("Sleeping...")
sleep(it)
println("Awake!")
}

Test:

sleepTest(1000)
print '''
Hmmm. That was... less than satisfying.
How about this instead?
'''

Thread.start {
(0..5).each {
println it
sleep(1000)
}
}
sleepTest(5000)

Output:

Sleeping...
Awake!

Hmmm. That was... less than satisfying
How about this instead?
Sleeping...
0
1
2
3
4
Awake!
5

[edit] Haskell

import Control.Concurrent
 
main = do seconds <- readLn
putStrLn "Sleeping..."
threadDelay $ round $ seconds * 1000000
putStrLn "Awake!"

[edit] HicEst

DLG(NameEdit = milliseconds, Button = "Go to sleep")
WRITE(StatusBar) "Sleeping ... "
SYSTEM(WAIT = milliseconds)
WRITE(Messagebox) "Awake!"

[edit] IDL

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

[edit] Icon and Unicon

procedure main()
 
repeat {
writes("Enter number of seconds to sleep :")
s := reads()
if s = ( 0 < integer(s)) then break
}
 
write("\nSleeping for ",s," seconds.")
delay(1000 * s)
write("Awake!")
end

[edit] J

Solution:

sleep =: 6!:3
 
sleeping=: monad define
smoutput 'Sleeping...'
sleep y
smoutput 'Awake!'
)

Example:

   sleeping 0.500          NB.  Sleep 500 milliseconds
Sleeping...
Awake!

[edit] Java

Works with: Java version 1.5+
 
import java.util.InputMismatchException;
import java.util.Scanner;
 
public class Sleep {
public static void main(final String[] args) throws InterruptedException {
try {
int ms = new Scanner(System.in).nextInt(); //Java's sleep method accepts milliseconds
System.out.println("Sleeping...");
Thread.sleep(ms);
System.out.println("Awake!");
} catch (InputMismatchException inputMismatchException) {
System.err.println("Exception: " + inputMismatchException);
}
}
}

[edit] 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.

<script>
 
setTimeout(function () {
document.write('Awake!')
}, prompt("Number of milliseconds to sleep"));
 
document.write('Sleeping... ');
 
</script>

[edit] Julia

 
print("Please enter sleep duration in seconds: ")
input = int(readline(STDIN))
println("Sleeping...")
sleep(input)
println("Awake!")
 

[edit] Lasso

Lasso has a built in sleep command that accepts milliseconds as an input.

stdoutnl('Sleeping...')
sleep(5000) // Sleep 5 seconds
stdoutnl('Awake!')

[edit] LabVIEW

Uses milliseconds. LabVIEW has no "main thread" so it must be forced with a sequence structure.
This image is a VI Snippet, an executable image of LabVIEW code. The LabVIEW version is shown on the top-right hand corner. You can download it, then drag-and-drop it onto the LabVIEW block diagram from a file browser, and it will appear as runnable, editable code.
Sleep.png

[edit] 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 "Void "V0
make "Long "U4
make "kernel32_handle libload "kernel32.dll
to Sleep :dwMilliseconds
end
external "Sleep [ Void Sleep Long] :kernel32_handle
 
to millisleep :n
print [Sleeping...]
Sleep :n  ; units: 1/1000th of a second
print [Awake.]
end

[edit] Liberty BASIC

Input "Please input the number of milliseconds you would like to sleep. "; sleeptime
Print "Sleeping..."
CallDLL #kernel32, "Sleep", sleeptime As long, ret As void
Print "Awake!"
 

[edit]

 
to sleep :n
print [Sleeping...]
wait :n  ; units: 1/60th of a second
print [Awake.]
end
 

[edit] Logtalk

Works when using SWI-Prolog, XSB, or YAP as the backend compilers:

 
:- object(sleep).
 
:- public(how_long/1).
 
how_long(Seconds) :-
write('Sleeping ...'), nl,
thread_sleep(Seconds),
write('... awake!'), nl.
 
:- end_object.
 

Sample output:

 
| ?- sleep::how_long(5).
Sleeping ...
... awake!
yes
 

[edit] Maple

sleep := proc(secs)
print("Sleeping...");
Threads:-Sleep(secs);
print("Awake!");
end proc:

[edit] Mathematica

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.

 
Sleep[seconds_] := (Print["Sleeping..."]; Pause[seconds]; Print["Awake!"];)
 

[edit] MATLAB / Octave

function sleep()
 
time = input('How many seconds would you like me to sleep for? ');
assert(time > .01);
disp('Sleeping...');
pause(time);
disp('Awake!');
 
end

[edit] Nemerle

using System;
using System.Console;
using System.Threading.Thread; // this is where the Sleep() method comes from
 
module Zzzz
{
Main() : void
{
def nap_time = Int32.Parse(ReadLine());
WriteLine("Sleeping...");
Sleep(nap_time); // parameter is time in milliseconds
WriteLine("Awake!");
}
}

[edit] NetRexx

/* NetRexx */
options replace format comments java crossref symbols nobinary
 
runSample(arg)
return
 
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method sleep(secs) public static binary
ms = (secs * 1000).format(null, 0) -- milliseconds, rounded to nearest integer
say 'Sleeping...'
do
Thread.sleep(ms)
catch ix = InterruptedException
say 'Sleep interrupted!'
ix.printStackTrace()
end
say 'Awake!'
return
 
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) public static
secs = -1
loop until \secs.datatype('N')
if secs > 0 then do
say 'Napping for' secs's'
say
sleep(secs)
end
say
say 'How many seconds do you want me to sleep? (enter something non-numeric to terminate)\-'
parse ask secs .
say
end
say
say 'Goodbye...'
say
return
 

[edit] NewLISP

(println "Sleeping..." )
(sleep 2000) ; Wait for 2 seconds
(println "Awake!")

[edit] Nimrod

import os, strutils
 
echo("Enter how long I should sleep (in milliseconds):")
var timed = parseInt(readLine(stdin).string)
echo("Sleeping...")
sleep(timed)
echo("Awake!")

[edit] Objective-C

Of course the same code of Sleep#C works for Objective-C. The following code uses a OpenStep derived framework (Cocoa, GNUstep...).

Works with: GNUstep
and
Works with: Cocoa
#import <Foundation/Foundation.h>
 
int main()
{
@autoreleasepool {
 
NSTimeInterval sleeptime;
printf("wait time in seconds: ");
scanf("%f", &sleeptime);
 
NSLog(@"sleeping...");
[NSThread sleepForTimeInterval: sleeptime];
NSLog(@"awakening...");
 
}
return 0;
}

[edit] Objeck

 
bundle Default {
class Test {
function : Main(args : System.String[]) ~ Nil {
if(args->Size() = 1) {
"Sleeping..."->PrintLine();
Thread->Sleep(args[0]->ToInt());
"Awake!"->PrintLine();
};
}
}
}
 

[edit] OCaml

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

or

#load "unix.cma";;
#directory "+threads";;
#load "threads.cma";;
let seconds = read_float ();;
print_endline "Sleeping...";;
Thread.delay seconds;; (* number is in seconds ... but accepts fractions *)
print_endline "Awake!";;

[edit] Oz

declare
class TextFile from Open.file Open.text end
StdIn = {New TextFile init(name:stdin)}
WaitTime = {String.toInt {StdIn getS($)}}
in
{System.showInfo "Sleeping..."}
{Delay WaitTime} %% in milliseconds
{System.showInfo "Awake!"}

[edit] PARI/GP

GP does not have threading built in and so cannot truly sleep; this is code for spin-idling.

[edit] gettime

The units are milliseconds.

sleep(ms)={
print("Sleeping...");
while((ms-=gettime()) > 0,);
print("Awake!")
};
 
sleep(input())

[edit] alarm

Works with: PARI/GP version 2.4.3 and above on Linux

The units are seconds.

sleep(s)={
print("Sleeping...");
alarm(s);
trap(alarmer,,while(1,));
print("Awake!")
};
 
sleep(input())

[edit] Pascal

See Delphi

[edit] Perl

seconds:

$seconds = <>;
print "Sleeping...\n";
sleep $seconds; # number is in seconds
print "Awake!\n";

microseconds and nanoseconds using the Time::HiRes module:

use Time::HiRes qw( usleep nanosleep );
 
$microseconds = <>;
print "Sleeping...\n";
usleep $microseconds;
print "Awake!\n";
 
$nanoseconds = <>;
print "Sleeping...\n";
nanosleep $nanoseconds;
print "Awake!\n";

It's also possible to sleep for fractional seconds by abusing the select function:

say "Sleeping...";
select undef, undef, undef, 0.5;
say "Awake!";

[edit] Perl 6

The sleep function argument is in units of seconds, but these may be fractional (to the limits of your system's clock).

my $sec = prompt("Sleep for how many microfortnights? ") * 1.2096;
say "Sleeping...";
sleep $sec;
say "Awake!";

Note that 1.2096 is a rational number in Perl 6, not floating point, so precision can be maintained even when dealing with very small powers of ten.

[edit] PHP

seconds:

$seconds = 42;
echo "Sleeping...\n";
sleep($seconds); # number is integer in seconds
echo "Awake!\n";

microseconds:

$microseconds = 42000000;
echo "Sleeping...\n";
usleep($microseconds); # number is integer in microseconds
echo "Awake!\n";

nanoseconds:

$nanoseconds = 42000000000;
echo "Sleeping...\n";
time_nanosleep($seconds, $nanoseconds); # first arg in seconds plus second arg in nanoseconds
echo "Awake!\n";

[edit] PicoLisp

(prinl "Sleeping..." )
(wait 2000) # Wait for 2 seconds
(prinl "Awake!")

As wait will continue executing background events, another possibility (for a complete stop) is calling some external program like

(prinl "Sleeping..." )
(call 'sleep 2) # Wait for 2 seconds
(prinl "Awake!")

[edit] PL/I

 
put ('sleeping');
delay (2000); /* wait for 2 seconds (=2000 milliseconds). */
put ('awake');
 

[edit] PowerShell

$d = [int] (Read-Host Duration in seconds)
Write-Host Sleeping ...
Start-Sleep $d
Write-Host Awake!

The -Milliseconds parameter to Start-Sleep can be used to allow for sub-second precision in sleeping.

[edit] Prolog

Works with SWI-Prolog.

rosetta_sleep(Time) :-
writeln('Sleeping...'),
sleep(Time),
writeln('Awake!').
 

[edit] Protium

Literate mode

<@ SAYLIT>Number of seconds: </@><@ GETVAR>secs</@>
<@ SAYLIT>Sleeping</@>
<@ ACTPAUVAR>secs</@>
<@ SAYLIT>Awake</@>

French variable-length opcodes

<# MontrezLittéralement>Number of seconds: </#><# PrenezUneValeurVariable>secs</#>
<# MontrezLittéralement>Sleeping</#>
<# AgissezFaireUnePauseVariable>secs</#>
<# MontrezLittéralement>Awake</#>

(Simplified) Chinese fixed-length opcodes

<@ 显示_字串_>Number of seconds: </@><@ 获取_变量_>secs</@>
<@ 显示_字串_>Sleeping</@>
<@ 运行_暂停动变量_>secs</@>
<@ 显示_字串_>Awake</@>

[edit] PureBasic

Sleeping is performed with Delay() and a value in milliseconds. The time is accurate to approximately +/- 15 milliseconds.

If OpenConsole()  
 
Print("Enter a time(milliseconds) to sleep: ")
x.i = Val(Input())
PrintN("Sleeping...")
Delay(x) ;in milliseconds
PrintN("Awake!")
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
Input()
CloseConsole()
EndIf

[edit] Python

import time
 
seconds = float(raw_input())
print "Sleeping..."
time.sleep(seconds) # number is in seconds ... but accepts fractions
print "Awake!"

[edit] R

The call to flush.console is only needed if buffering is turned on. See FAQ for R on windows. The time is given in seconds (fractions allowed, resolution is system dependent).

 
sleep <- function(time=1)
{
message("Sleeping...")
flush.console()
Sys.sleep(time)
message("Awake!")
}
 
sleep()
 

[edit] Racket

 
#lang racket
(displayln "Enter a time (in seconds): ")
(define time (read))
(when (number? time)
(displayln "Sleeping...")
(sleep time)
(displayln "Awake!"))
 

[edit] REBOL

rebol [
Title: "Sleep Main Thread"
Date: 2009-12-15
Author: oofoe
URL: http://rosettacode.org/wiki/Sleep_the_Main_Thread
]

 
naptime: to-integer ask "Please enter sleep time in seconds: "
print "Sleeping..."
wait naptime
print "Awake!"

[edit] Retro

Retro has no fine grained timer; so we have to make due with seconds.

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

[edit] REXX

Not all REXX interpretors have the DELAY built-in function.

/*REXX program to sleep   x   seconds (base in the argument). */
parse arg secs . /*get a (possible) argument. */
secs=word(secs 0,1) /*if not present, assume 0 (zero)*/
say 'Sleeping' secs "seconds." /*tell 'em what's happening. */
call delay(secs) /*snooze. Hopefully, a short nap*/
say 'Awake!' /*and tell 'em we're running. */

output after the following was used for input: </tt> 4.7 </tt>

Sleeping 4.7 seconds.
Awake!

[edit] Ruby

seconds = gets.to_f
puts "Sleeping..."
sleep(seconds) # number is in seconds ... but accepts fractions
# Minimum resolution is system dependent.
puts "Awake!"


[edit] Scala

Library: Scala
object Sleeper extends App {
print("Enter sleep time in milli sec: ")
val ms = scala.io.StdIn.readInt()
println("Sleeping...")
val sleepStarted = scala.compat.Platform.currentTime
Thread.sleep(ms)
println(s"Awaked after [${scala.compat.Platform.currentTime - sleepStarted} ms]1")
}

[edit] Scheme

Many Scheme implementations support srfi-18, a multithreading library which provides a 'thread-sleep!' function. The following works in Chicken Scheme:

 
(use format)
(use srfi-18)
 
(format #t "Enter a time (in seconds): ")
(let ((time (read))) ; converts input to a number, if possible
(if (number? time)
(begin
(format #t "Sleeping...~&")
(thread-sleep! time)
(format #t "Awake!~&"))
(format #t "You must enter a number~&")))
 

Scheme implementations also provide alternative approaches. For example, Chicken Scheme has a 'posix' library which includes a 'sleep' function.

[edit] Seed7

The 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 "seed7_05.s7i";
include "duration.s7i";
 
const proc: main is func
local
var integer: secondsToSleep is 0;
begin
write("Enter number of seconds to sleep: ");
readln(secondsToSleep);
writeln("Sleeping...");
wait(secondsToSleep . SECONDS);
writeln("Awake!");
end func;

[edit] Smalltalk

Works with: Pharo
t := (FillInTheBlankMorph request: 'Enter time in seconds') asNumber.
Transcript show: 'Sleeping...'.
(Delay forSeconds: t) wait.
Transcript show: 'Awake!'.
 
Works with: Smalltalk/X
t := (Dialog request: 'Enter time in seconds') asNumber.
Transcript show: 'Sleeping...'.
(Delay forSeconds: t) wait.
Transcript show: 'Awake!'.
 

(of course, you can "Smalltalk at:#FillInTheBlankMorph put:Dialog", to be source compatible with Pharo)

[edit] Standard ML

(TextIO.print "input a number of seconds please: ";
let val seconds = valOf (Int.fromString (valOf (TextIO.inputLine TextIO.stdIn))) in
TextIO.print "Sleeping...\n";
OS.Process.sleep (Time.fromReal seconds); (* it takes a Time.time data structure as arg,
but in my implementation it seems to round down to the nearest second.
I dunno why; it doesn't say anything about this in the documentation *)

TextIO.print "Awake!\n"
end)

[edit] Suneido

function (time)
{
Print("Sleeping...")
Sleep(time) // time is in milliseconds
Print("Awake!")
}

[edit] Tcl

Blocking example (the process is blocked preventing any background activity).

puts -nonewline "Enter a number of milliseconds to sleep: "
flush stdout
set millis [gets stdin]
puts Sleeping...
after $millis
puts Awake!

A non-blocking example where background activity will occur.

puts -nonewline "Enter a number of milliseconds to sleep: "
flush stdout
set millis [gets stdin]
set ::wakupflag 0
puts Sleeping...
after $millis set ::wakeupflag 1
vwait ::wakeupflag
puts Awake!

[edit] TI-89 BASIC

This example is in need of improvement:
Do something less wasteful than a busy wait, if possible.
Local dur_secs,st0,st,seconds
Define seconds() = Func
  Local hms
  getTime()→hms
  Return ((hms[1] * 60 + hms[2]) * 60) + hms[3]
EndFunc
ClockOn
  
Prompt dur_secs
Disp "Sleeping..."
seconds()→st
st→st0
While when(st<st0, st+86400, st) - st0 < dur_secs
  seconds()→st
EndWhile
Disp "Awake!"

[edit] Toka

This makes use of the sleep() function from libc which suspends execution for a specified number of seconds.

1 import sleep as sleep()
[ ." Sleeping...\n" sleep() drop ." Awake!\n" bye ] is sleep

45 sleep

[edit] TUSCRIPT

 
$$ MODE TUSCRIPT
secondsrange=2
PRINT "Sleeping ",secondsrange," seconds "
WAIT #secondsrange
PRINT "Awake after Naping ",secondsrange, " seconds"
 

[edit] UNIX Shell

printf "Enter a time in seconds to sleep: "
read seconds
echo "Sleeping..."
sleep "$seconds"
echo "Awake!"

This uses the sleep(1) command. POSIX sleep(1) only takes an integer, as in sleep 2, so you can only sleep for a whole number of seconds. Some systems extend sleep(1) to take a decimal fraction, as in sleep 2.5.

[edit] VBA

 
Function Sleep(iSecsWait As Integer)
Debug.Print Now(), "Sleeping..."
Application.Wait Now + iSecsWait / 86400 'Time is stored as fractions of 24 hour day
Debug.Print Now(), "Awake!"
End Function
 


[edit] 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!"
 

[edit] Vedit macro language

#1 = Get_Num("Sleep time in 1/10 seconds: ")
Message("Sleeping...\n")
Sleep(#1)
Message("Awake!\n")

[edit] zkl

seconds:=ask("Seconds to sleep: ").toFloat();
println("Sleeping...");
Atomic.sleep(seconds); # float, usually millisecond resolution
println("Awake!");
Personal tools
Namespaces

Variants
Actions
Community
Explore
Misc
Toolbox