A tool for long-term optimization of cogeneration systems is developed that is based on mixed integer linear programming and Lagrangian relaxation. We use a general approach without heuristics to solve the optimization problem of the unit commitment problem and load dispatch. The possibility to buy and sell electric power at a spot market is considered as well as the possibility to provide secondary reserve. The tool has been tested on a demonstration system based on an existing combined heat and power (CHP) system with extraction-condensing steam turbines, gas turbines, boilers for heat production and district heating networks. The key feature of the model for obtaining solutions within reasonable times is a suitable division of the whole optimization period into overlapping subperiods. Using Lagrangian relaxation the tool can be applied to large CHP systems. For the demonstration model almost optimal solutions were found.