Essentially the wire(s) that sit in your heart work as two-way leads. They are able to sense any electrical activity in the the heart muscle telling the pacing box what your heart is actually doing. They also conduct electricity from the pacing box down to the heart muscle to stimulate it to contract if it hasn't put in a spontaneous beat.
So, if for example, your pacemaker was set to pace if your heart rate fell below 60 beats per minute, then if electrical activity was not detected in the heart muscle for more than a second the pacemaker would put a pulse of electricity down the wire, stimulating a heart beat. If on the other hand after half a second the wire sensed some spontaneous electricity in the heart muscle the pacemaker wouldn't put out any electrical pulse until a subsequent period of electrical silence of just over one second had passed.
In this way the heart is only stimulated to beat when necessary. The functioning of single and dual chamber pacemakers are essentially the same in this respect although more complicated in a dual chamber pacemaker as both wires can sense and pace and therefore the electronic control mechanisms of the device are significantly more sophisticated.