A general ergodic theorem