I'm struggling to understand one thing about preemption. Citing Wikipedia:
In computing, preemption (more correctly pre-emption) is the act of temporarily interrupting a task being carried out by a computer system, without requiring its cooperation, and with the intention of resuming the task at a later time. Such a change is known as a context switch. It is normally carried out by a privileged task or part of the system known as a preemptive scheduler, which has the power to preempt, or interrupt, and later resume, other tasks in the system.
So, basically, they say the scheduler can interrupt the current running task. How is that even possible? CPU is running the code of this task at the moment, not the code of scheduler. So how a scheduler can do anything?
My guess is that there must be some kind of a hardware timer which physically interrupts CPU after some time has passed and give control back to scheduler. Is this correct? Is there any documentation where I can read about it in more detail?
Any answers will be highly appreciated.
Your guess is correct. In most operating systems, there is a timer interrupt that runs privileged code in the kernel on some fixed frequency. This privileged code can decide to either (a) return to the originally running code, or (b) save the context and start running some other code.
There are other conditions which can cause a context switch, such as a request to read from I/O where the process would have to wait for the I/O be ready. The kernel will probably switch to some other task while the first is waiting.
You may also be interested in reading about the so-called tickless kernel.