Check for blocked queries periodically and cancel them
You can do this by querying pg_stat_activity on newer PostgreSQL versions that record the query start time.

See pg_stat_activity in the PostgreSQL manual.

Use pg_cancel_backend to cancel the query, or pg_terminate_backend to close the connection running the query.

However, I strongly recommend that you instead fix the problem so that your queries don't get blocked. Look at pg_locks when it's stuck, determine why it's getting stuck, and fix the problem. Read the PostgreSQL manual chapter on explicit locking, and the wiki entries on lock monitoring.