First I will assume older engines with no electronic systems.
The distributor is usually driven from the camshaft and is often also the drive to the oil pump, so the shaft comes up from the gear driven off the camshaft and descends down to the oil pump, usually to save cost and weight.
Once you have the camshaft correctly timed and it is driven at half the crankshaft speed then that will be the correct speed for the distributor. Then all you have to do is set the timing so that cylinder 1 fires at approximately 5 degrees before top dead centre.
Once you have electronic control then there can be several sensors involved: crank position sensors, cam position sensors, throttle position etc. For crank position, Hall effect sensors can often be used, but the trick is that there are two or three magnets a specific distance apart on the flywheel so the ecu can have a rapid update on crankshaft speed changes.
The ignition timimg and fuel timing are controlled by the position of the crank, cam and various sensors measuring the engine load, speed, temperature etc
The injection timing, not only the start time but the duration of injection is controlled by the ecu (engine control unit) based on the parameters listed above which are compared to a characteristic map held in memory. There was some clear information by Bosch when J and K Jetronic systems were first around and they had some good block diagrams explaining the function and also how to test for faults.
You might find these interesting to read: