Managing of real-time energy in microgrids connected to grid is a relatively new technology that is becoming increasingly popular in the energy industry. It enables microgrids to connect with each other and with a wider electrical grid to increase efficiency and improve energy resiliency while reducing costs and emissions. It also enables the grid-connected microgrids to dynamically adjust to changing conditions, allowing for upgraded energy infrastructure and improved energy security. However, identifying an accurate and efficient approach for real-time energy management for microgrids is critical. In this regards, this paper introduces a modified metaheuristic, the Boosted Beluga Whale Optimizer (BBWO), for the application of real-time energy management to optimize battery controlling of a CM (community microgrid). This amendment involves changes to the cost function so that it better captures the battery charging/discharging operations. A function of dynamic penalty is then suggested for the sake of further improves the cost function. The suggested cost function effectiveness is determined through a real-time case study, in operational cost over a 96h time horizon. From the results, the battery's charging/discharging cycles provides lower operational expenses of $29.70 over a 96-hour time horizon. Further, the proposed innovative penalty function encourages optimal charging of the battery from RESs and the grid utility and could reduce the cost of the objective function significantly. It was also demonstrated that the battery is constantly trying to maintain full charge, which requires an expenditure of $33.14 in electricity. This cost is still less than the original cost, but it allows for high energy levels to be maintained across all time periods. Additionally, this also prevents any issues stemming from low battery levels and maximizes the life of the battery. Overall, the regularized BBWO algorithm, with the offered cost function adapted to the needs of the society, is a suitable solution for real-time energy management.