Monday, January 16, 2017

Hack 4.8 Putting Your SAS Programs to Sleep

SAS Programming Professionals,

Did you know that you can actually put your SAS programs to sleep?

The SLEEP function suspends execution of your SAS program (puts it to sleep) for the duration of time that you specify in the function.  This function comes in handy when you need to programmatically pause your SAS programs for various reasons.  One such reason is to wait for an asynchronous system event to occur before your SAS program continues.  For example, if you use an X statement to invoke an operating system command, you could put your program to SLEEP for the duration that it takes for that command to complete.

The general form of the SLEEP function is:  Q = SLEEP(N); …where:

·        Q = any SAS variable

·        N = the number of seconds to wait.  The maximum is 46 days!  See the documentation if you want to specify other intervals, such as micro-seconds.

Here is an example of the SLEEP function in action:

options noxwait noxsync xmin;

x '"C:\Program Files\Microsoft Office\Office11\excel.exe"';

data _null_;

filename comma1 dde 'excel|system';

data _null_;
 file comma1;
 put '[open("D:\MCR\t_excel.xls")]';

data _null_;

…Other SAS code to populate the Excel spreadsheet…

The overall thrust of this example is to use DDE to open and populate an Excel spreadsheet from a SAS program.  First, we use the SAS X statement to send a command to Windows to open Excel.  Secondly, we put our program to sleep for 10 seconds in a DATA _NULL_ step to give Windows enough time to complete opening Excel.  Next, the FILENAME statement sets up our DDE “environment” and the second DATA _NULL_ creates our spreadsheet in the opened Excel program.  Then, we put our SAS program to sleep a second time to give Excel enough time to create the t_excel.xls spreadsheet in the opened Excel program in the aforementioned DATA _NULL_ step.

If you are tired of having your programs fail due to SAS-generated asynchronous tasks not completing on time, consider using the SLEEP function!

Best of luck in all your SAS endeavors!

(aka Michael A. Raithel)
Author of the new cult classic for computer programmers:  It Only Hurts When I Hit <ENTER>
Print edition: 
Kindle edition: 

The hack above is an excerpt from the book:  Did You Know That?  Essential Hacks for Clever SAS Programmers