We propose a scheme to dynamically realize a quantum memory based on the toric code. The code is generated from qubit systems with typical two-body interactions (Ising, XY, Heisenberg) using periodic, NMR-like, pulse sequences. It allows one to encode the logical qubits without measurements and to protect them dynamically against the time evolution of the physical qubits. A weakly coupled cavity mode mediates a long-range attractive interaction between the stabilizer operators of the toric code, thereby suppressing the creation of thermal anyons. This significantly increases the lifetime of the memory compared to the code with noninteracting stabilizers. We investigate how the fidelity, with which the toric code is realized, depends on the period length T of the pulse sequence and the magnitude of possible pulse errors. We derive an optimal period T_opt that maximizes the fidelity.