Microgrids are becoming one of the main components of future smart grids. Ensuring their optimal and stable operation is of crucial importance and can be a challenging task. In this paper, two optimization algorithms are implemented for scheduling the microgrid operation in grid-connected and islanded modes, according to the priorities and objectives in each mode. For achieving an optimal operation at each mode, the proposed scheme is able to shed loads, define the generation level of the photovoltaics and regulate the charging/ discharging level of the Energy Storage System (ESS). The effectiveness of the proposed scheduling is demonstrated through an analytical realtime simulation, where various transitions between the gridconnected and islanded modes are considered. The results indicate that the proposed scheme is able to regulate successfully the energy flows of the microgrid even under various transitions.