I have a server application and a database. Several server instances can be started simultaneously, but all the data comes from the same database (on some servers it is postgresql, in other cases ms sql server).
My application is running a process that can take several hours. I need to make sure that this process is performed only one at a time. If one server is processing, no other server instance can be processed until the first is completed.
A process depends on a single table (let's call it "ProcessTable"). What I do, before any server starts the clock process, I set the boolean flag in the ProcessTable, which indicates that this record is “locked” and is being processed (not all records in this table are processed / locked, so I need mark each entry that is necessary for the process). Therefore, when the next server instance arrives while the previous instance is still being processed, it sees the logical flags and throws an exception.
The problem is that two server instances can be activated almost simultaneously, and when both check the ProcessTable, no flags can be set, but both servers are actually in the process of “setting” flags, but since the transaction has not yet been completed for any process , no process will see a lock being executed by another process. This is due to the fact that the locking mechanism itself can take several seconds, therefore there is such a window of possibilities in which two servers can be processed simultaneously.
It looks like I need one entry in my "Settings" table, which should store the logical flag "LockInProgress". Therefore, before even the server can lock the necessary entries in ProcessTable, you must first make sure that it has full rights to lock by checking the "LockInProgress" column in the "Settings" table.
So my question is: how can I prevent the two servers from both LockInProgress columns from changing in the settings table at the same time ... or am I wrong about this?
Note that I need to support both postgresql and ms sql servers, as some servers use one database and some servers use another.
Thanks in advance...