postgresqlでスリープ処理

概要

CentOS 6.6上のpostgresバージョンは9.4で確認しました。

postgresでは関数pg_sleepを使ってsleep処理を実行することができます。

test=# select CURRENT_TIMESTAMP; select pg_sleep(10); select CURRENT_TIMESTAMP;
              now
-------------------------------
 2015-10-11 04:55:12.504113+02
(1 Zeile)

 pg_sleep
----------

(1 Zeile)

              now
-------------------------------
 2015-10-11 04:55:22.515183+02
(1 Zeile)
しかし、function内では関数pg_sleepをselectではなくperformで使う必要があります。
関数の呼び出しにおいて、副次的な成果を取得できるが、結果は無用である場合です。 このような時PL/pgSQLでは、PERFORM文を使用してください。
test=# CREATE OR REPLACE FUNCTION test_pg_sleep(INTEGER, INTEGER) RETURNS VOID AS $$
test$# DECLARE
test$# loops ALIAS FOR $1;
test$# delay ALIAS FOR $2;
test$# BEGIN
test$# for i IN 1..loops LOOP
test$# RAISE INFO 'Current timestamp: %', timeofday()::TIMESTAMP;
test$# RAISE INFO 'Sleep % seconds', delay;
test$# PERFORM pg_sleep(delay);
test$# END LOOP;
test$# END;
test$# $$ LANGUAGE 'plpgsql' STRICT;
CREATE FUNCTION
test=# SELECT test_pg_sleep(3,10);
INFO:  Current timestamp: 2015-10-11 05:04:19.697531
INFO:  Sleep 10 seconds
INFO:  Current timestamp: 2015-10-11 05:04:29.708706
INFO:  Sleep 10 seconds
INFO:  Current timestamp: 2015-10-11 05:04:39.718359
INFO:  Sleep 10 seconds
 test_pg_sleep
---------------

(1 Zeile)

参考資料