How to run block of code in Postgres asynchronously (like a job)?

1k Views Asked by At

Can we execute a block of code outside of current session? In other words, delegate the execution to another working thread, something like a dbms_job.submit in Oracle.

I found only solutions involving external tools like Cron, but do not see any options to do it using PostgreSQL DBMS itself.

Example of simple long running block that I would like to run without blocking my current session:

DO
$do$
begin
   FOR i IN 1..1000000
   loop
      // some long running inserts
      insert into my_table(x) values (i);
      commit;
   end loop;
end $do$;
2

There are 2 best solutions below

2
On BEST ANSWER

You can only have a single statement at a time running in a single PostgreSQL database session. The solution is to start a second session: then one session can execute the script, and you can concurrently do other work in the other session.

0
On

You should have a look to this new PostgreSQL extension pg_dbms_job, it implements all features provided by Oracle DBMS_JOB with the same procedures like dbms_job.submit().