Sleep: Difference between revisions

From Rosetta Code
Content added Content deleted
No edit summary
(added Batch File)
Line 35: Line 35:
PRINT "Awake!"</lang>
PRINT "Awake!"</lang>
"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|Batch File}}==
The usual way to do this is to use the <code>ping</code> utility which waits a second between multiple tries. To wait ''n'' seconds one tells <code>ping</code> to make ''n''&nbsp;+&nbsp;1 tries and redirects the output:

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

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

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


=={{header|C}}==
=={{header|C}}==

Revision as of 10:27, 15 April 2010

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.

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.

<lang ada>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;</lang>

AutoHotkey

<lang AutoHotkey>TrayTip, sleeping, sleeping sleep, 2000 ; 2 seconds TrayTip, awake, awake Msgbox, awake</lang>

BASIC

Works with: QuickBasic version 4.5

<lang qbasic>INPUT sec 'the SLEEP command takes seconds PRINT "Sleeping..." SLEEP sec PRINT "Awake!"</lang> "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.

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

<lang dos>@echo off set /p Seconds=Enter the number of seconds to sleep: set /a Seconds+=1 echo Sleeping ... ping -n %Seconds% localhost >nul 2>&1 echo Awake!</lang> 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 XP

<lang dos>@echo off set /p MilliSeconds=Enter the number of milliseconds to sleep: echo Sleeping ... ping -n 1 -w %MilliSeconds% 1.2.3.4 >nul 2>&1 echo Awake!</lang>

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

Works with: Windows Vista

<lang dos>@echo off set /p Seconds=Enter the number of seconds to sleep: echo Sleeping ... timeout /t %Seconds% /nobreak >nul echo Awake!</lang>

C

Works with: POSIX

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

<lang c>#include <stdio.h>

  1. include <unistd.h>

int main() {

 unsigned int seconds;
 scanf("%u", &seconds);
 printf("Sleeping...\n");
 sleep(seconds);
 printf("Awake!\n");
 return 0;

}</lang>

C++

<lang cpp>#include <unistd.h>

  1. 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;

}</lang>

C#

<lang csharp>using System; using System.Threading;

class Program {

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

}</lang>


Clojure

<lang clojure>(defn sleep [ms] ; time in milliseconds

 (println "Sleeping...")
 (Thread/sleep ms)
 (println "Awake!"))
call it

(sleep 1000)</lang>


Common Lisp

<lang lisp>(defun test-sleep ()

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

(test-sleep)</lang>

D

<lang d>import std.c.time; import std.stdio; import std.string; void main() {

 writef("Enter a time(seconds) to sleep: ");
 writefln("Sleeping...");
 sleep(atoi(readln())*1000);
 writefln("Awake!");

}</lang>

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.

<lang e>def sleep(milliseconds :int, nextThing) {

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

}</lang>

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.

<lang eiffel >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</lang>

Output (sleeping 10 seconds):

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

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: <lang erlang>main() ->

   io:format("Sleeping...~n"),
   timer:sleep(1000), %% in milliseconds
   io:format("Awake!~n").</lang>

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: <lang erlang>main() ->

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

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

Factor

<lang factor>USING: calendar io math.parser threads ;

read-sleep ( -- )
   readln string>number seconds
   "Sleeping..." print
   sleep
   "Awake!" print ;</lang>

Forth

<lang forth>: sleep ( ms -- )

 ." Sleeping..."
 ms
 ." awake." cr ;</lang>

Haskell

<lang haskell>import Control.Concurrent

main = do seconds <- readLn

         putStrLn "Sleeping..."
         threadDelay $ round $ seconds * 1000000
         putStrLn "Awake!"</lang>

HicEst

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

IDL

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

J

Solution: <lang j>sleep =: 6!:3

sleeping=: monad define

 smoutput 'Sleeping...'
 sleep y
 smoutput 'Awake!'

)</lang>

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

Java

<lang java>import java.util.Scanner;

public class Sleep{ public static void main(String[] args) throws InterruptedException{ Scanner input = new Scanner(System.in); int ms = input.nextInt(); //Java's sleep method accepts milliseconds System.out.println("Sleeping..."); Thread.sleep(ms); System.out.println("Awake!"); } }</lang>

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.

<lang html><html><head><title>RC Sleep The Main Thread</title></head><body> <form>

   <button type="button" onclick="
       function write(s) {
         var l = document.getElementById('log');
         l.appendChild(document.createTextNode(+s));
         l.appendChild(document.createElement('br'));
       }
       
       write('Sleeping...');
       setTimeout(function () {
        write('Awake!');
       }, parseFloat(document.getElementById('delay').value));
       
   ">Sleep</button> for <input id="delay"> milliseconds.

</form>


</body></html></lang>

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

Objective-C

This example is incorrect. Please fix the code and remove this message.

Details: Only the core of the task is implemented, not the task as a whole.

<lang objc>[NSThread sleepForTimeInterval:numSeconds];

// number of seconds can be fractional (it's a double)</lang>

OCaml

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

or <lang ocaml>#load "unix.cma";;

  1. directory "+threads";;
  2. load "threads.cma";;

let seconds = read_float ();; print_endline "Sleeping...";; Thread.delay seconds;; (* number is in seconds ... but accepts fractions *) print_endline "Awake!";;</lang>

Oz

<lang 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!"}</lang>

Perl

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

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

$microseconds = <>; print "Sleeping...\n"; usleep $microseconds; print "Awake!\n";

$nanoseconds = <>; print "Sleeping...\n"; nanosleep $nanoseconds; print "Awake!\n";</lang>

PHP

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

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

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

PicoLisp

<lang PicoLisp>(prinl "Sleeping..." ) (wait 2000) # Wait for 2 seconds (prinl "Awake!")</lang> As wait will continue executing background events, another possibility (for a complete stop) is calling some external program like <lang PicoLisp>(prinl "Sleeping..." ) (call 'sleep 2) # Wait for 2 seconds (prinl "Awake!")</lang>

PL/I

<lang PL/I> put ('sleeping'); delay (2000); /* wait for 2 seconds (=2000 milliseconds). */ put ('awake'); </lang>

PowerShell

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

PureBasic

Sleeping is performed with Delay() and a value in milliseconds. The time is accurate to approximately +/- 15 milliseconds. <lang PureBasic>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</lang>

Python

<lang python>import time

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

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). <lang R> sleep <- function(time=1) {

  message("Sleeping...")
  flush.console()      
  Sys.sleep(time)
  message("Awake!")

}

sleep() </lang>

REBOL

<lang 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!"</lang>

Ruby

<lang ruby>seconds = gets.to_f puts "Sleeping..." sleep(seconds) # number is in seconds ... but accepts fractions

  1. Minimum resolution is system dependent.

puts "Awake!"</lang>

Standard ML

<lang ocaml>(TextIO.print "input a number of seconds please: "; let val seconds = valOf (Int.fromString (valOf (TextIO.inputLine TextIO.stdIn))) in

 TextIO.print "Sleeping...\n";
 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)</lang>

Suneido

<lang Suneido>function (time)

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

Tcl

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

A non-blocking example where background activity will occur. <lang tcl>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!</lang>

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!"

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

UNIX Shell

Works with: Bash

<lang bash>read -p "Enter a time in seconds to sleep: " seconds echo "Sleeping..." sleep $seconds echo "Awake!"</lang>

Vedit macro language

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