Switch to new model for managing automatic events in the database.

This should fix the double-events bug. It is though probably not resistant
to race conditions when more than one Dynamics object accesses the database.
Some more explicit session locking is required.