Complex wireless sensor network applications as those in Internet-of-Things or in-network processing are pushing the requirements for energy efficiency and data processing drastically. Energy-aware task allocation becomes crucial to efficiently distribute the tasks of the applications for the nodes to extend the network lifetime. In this paper, we propose a distributed optimal on-line task allocation algorithm, by considering the energy cost of communicating, computing, sensing, and sleeping activities, to optimally balance the workload distribution among the sensor nodes. Through an in-depth analysis, this paper proves that the optimal partition solution for each node consists of at most two partition cuts with the corresponding weights. This observation enables the proposed on-line algorithm to maximize the network lifetime with low execution complexity. The simulation results show that our proposed algorithm extends the network lifetime by 12.26 times compared with the strategy of no scheduling, which is 2.22 times more than previous off-line task allocation methods. Moreover, the energy spent on executing the on-line algorithm is so small that it can be neglected.