Sleep

The Fortran standard does not include any routine for pausing a program for a given time. Most compilers, like GNU Fortran, provide a routine through extensions:

! sleep.f90
program main
    implicit none
    integer :: i

    do i = 1, 10
        print '(a)', 'zzz ...'
        call sleep(2)
    end do
end program main

GNU Fortran’s sleep() routine pauses the process for the given time in seconds. Other compilers may provide similar extensions. As an alternative, a compiler-independent interface to the POSIX routine sleep(3) can be written, making the call compatible to all POSIX-compliant operating systems. However, the Fortran Standard Library provides a platform-independent routine to sleep a given time measured in milliseconds.

POSIX

In order to sleep for less than a second, one might consider an ISO C binding interface to the POSIX function usleep(3), which pauses the process for a given interval in microseconds. The library fortran-unix includes the necessary Fortran interface binding, but we can instead just add a module that contains the interface declaration:

! example.f90
module posix
    use, intrinsic :: iso_c_binding, only: c_int, c_int32_t
    implicit none

    interface
        ! int usleep(useconds_t useconds)
        function c_usleep(useconds) bind(c, name='usleep')
            import :: c_int, c_int32_t
            integer(kind=c_int32_t), value :: useconds
            integer(kind=c_int)            :: c_usleep
        end function c_usleep
    end interface
end module posix

program main
    use :: posix
    implicit none
    integer :: i, rc, t

    t = 500 * 1000 ! 500 milliseconds

    do i = 1, 10
        print '(a)', 'zzz ...'
        rc = c_usleep(t)
    end do
end program main

Be aware that usleep(3) has been declared obsolete. It is recommended to use nanosleep(2), but a little more complex derived type binding is required then.

Fortran Standard Library

The Fortran Standard Library features a platform-independent implementation of the sleep() routine that delays the program execution for a given time in milliseconds.

! sleep.f90
program main
    use :: stdlib_system, only: sleep
    implicit none
    integer :: i

    do i = 1, 10
        print *, 'zzz ...'
        call sleep(500)
    end do
end program main

Link the example program against the static library libstdlib.a:

$ gfortran10 -o sleep sleep.f90 libstdlib.a

References