Reducing the primary energy consumption in buildings and simultaneously increasing self-consumption from renewable energy sources in nearly-zero-energy buildings, as per the 2010/31/EU directive, is crucial nowadays. This work solved the problem of nearly zeroing the net grid electrical energy in buildings in real time. This target was achieved using linear programming (LP)—a convex optimization technique leading to global solutions—to optimally decide the daily charging or discharging (dispatch) of the energy storage in an adaptive manner, in real time, and hence control and minimize both the import and export grid energies. LP was assisted by equally powerful methods, such as artificial neural networks (ANN) for forecasting the building’s load demand and photovoltaic (PV) on a 24 hour basis, and genetic algorithm (GA)—a heuristic optimization technique—for driving the optimum dispatch. Moreover, to address the non-linear nature of the battery and model the energy dispatch in a more realistic manner, the proven freeware system advisor model (SAM) of National Renewable Energy Laboratory (NREL) was integrated with the proposed approach to give the final dispatch. Assessing the case of a building, the results showed that the annual hourly profile of the import and export energies was smoothed and flattened, as compared to the cases without storage and/or using a conventional controller. With the proposed approach, the annual aggregated grid usage was reduced by 53% and the building’s annual energy needs were covered by the renewable energy system at a rate of 60%. It was therefore concluded that the proposed hybrid methodology can provide a tool to maximize the autonomy of nearly-zero-energy buildings and bring them a step closer to implementation.