The invention discloses a method for extracting coal bed gas under wells through the alternate cooling and heating function, and belongs to the technical field of unconventional oil and gas production. The method comprises the steps that (1) vertical well drilling is carried out from the ground, a well pattern is arranged, the wells are drilled till a coal layer, the number of the wells is largerthan or equal to 2, at least on well in the arranged well pattern is a work well, and the other wells are adopted as gas extraction and production wells; (2), a heat source is input into the coal layers from the work well, the temperature of the heat source is adjusted to range from 380 DEG C to 450 DEG C, the coal layer is heated, and when the temperature of the coal layer is larger than or equalto 350 DEG C, heating is stopped; (3), liquid nitrogen is injected into the coal layer through the work well, the injection amount of the liquid nitrogen is determined according to different geological conditions and coal body features, and after the liquid nitrogen is vaporized, refrigeration is finished; and (4), the step 2 and the step 3 are repeated many times, the coal layer is located in analternate work state all the time, and coal layer gas is extracted in the gas extraction and production wells. According to the method, coal layer gas extraction can be effectively carried out, and the coal layer gas extraction speed and the extraction rate are increased.