President Trump ended the second government shutdown of his tenure early Friday morning, signing a sweeping spending bill hours after Congress backed the bipartisan budget deal that stands to add hundreds of billions of dollars in federal spending on the military, domestic programs and disaster relief.

The 240-to-186 House vote gaveled to a close just after 5:30 a.m., nearly four hours after the Senate cleared the legislation on a vote of 71 to 28, with wide bipartisan support.

But action did not come soon enough to avoid a brief government shutdown — the second in three weeks — thanks to a one-man protest from Sen. Rand Paul (R-Ky.), who delayed the Senate vote past midnight to mark his opposition to an estimated $320 billion addition to the federal budget deficit.

Trump tweeted that he signed the bill, officially ending the brief shutdown.

“Just signed Bill,” he wrote. “Our Military will now be stronger than ever before. We love and need our Military and gave them everything — and more. First time this has happened in a long time. Also means JOBS, JOBS, JOBS!”

The shutdown was so unanticipated that the Office of Management and Budget didn’t tell federal agencies to prepare for it until Thursday evening. The closure is likely to end up being brief and having only a slight impact on federal workers and the public.

The bill would reopen the government while showering hundreds of billions of dollars on defense and domestic priorities, speeding disaster aid to hurricane-hit regions, and lifting the federal borrowing limit for a year. While the legislation sets out broad budget numbers for the next two fiscal years, lawmakers face yet another deadline on March 23 — giving congressional appropriators time to write a detailed bill doling out funding to government agencies.

Still, lawmakers’ inability to keep open the government underpinning the world’s largest economy pointed to acute legislative dysfunction that has paralyzed Congress and forced the government to operate on one short-term spending bill after another since the fiscal year began Oct. 1.

Last month, the government shut down for three days in a dispute over undocumented immigrants brought to the country as kids, reopening when Senate Democrats accepted assurances from Senate Majority Leader Mitch McConnell (R-Ky.) that he would hold a floor debate on immigration this month.

The budget deal passed Friday was meant to break the cycle of budget dysfunction — before it, too, ran into dysfunction.

Earlier in the week, the spending deal appeared primed for easy passage as McConnell and Minority Leader Charles E. Schumer (D-N.Y.) unveiled it jointly on the Senate floor with a bipartisan flourish and mutual praise. But it began to run into trouble Thursday, as House conservatives rebelled over excessive deficit spending and House liberals fumed that this bill, too, failed to protect “dreamers” — undocumented immigrants brought to the country as children who face losing work permits granted by President Barack Obama under the Deferred Action for Childhood Arrivals program (DACA) but rescinded by Trump.

Then, as an expected vote approached in the Senate, Paul began to throw up roadblocks, demanding a vote on his amendment that would demonstrate how the two-year budget deal breaks past pledges to rein in federal spending.

GOP leaders refused to allow him to offer the amendment, arguing that if Paul got an amendment vote, many other senators might want one, too. Paul, in turn, refused to allow the vote to go forward, making use of Senate rules that allow individual senators to slow down proceedings that require the consent of all.

“I can’t in all good honesty, in all good faith, just look the other way because my party is now complicit in the deficits,” Paul said on the Senate floor as evening pushed into night.

Meanwhile, potentially bigger problems surfaced in the House, where liberals led by Minority Leader Nancy Pelosi (D-Calif.) were incensed that the plight of young undocumented immigrants who face the threat of deportation was not addressed in the spending bill.

Pelosi announced she would vote against the bill. And despite initially suggesting that she would not be urging fellow Democrats to follow her lead, she increasingly appeared to be doing exactly that.

At a closed-door evening meeting of House Democrats, Pelosi told lawmakers to “use our leverage,” according to one House Democrat in the room, who spoke on the condition of anonymity to disclose the private conversation.

“We have a moment,” she said. “They don’t have the votes.”

Pelosi is under intense pressure from immigration activists and liberals in her caucus to take a stand for the dreamers because they face losing deportation protections under the Trump administration.

Supporters of these immigrants have watched in growing outrage as Democrats have failed repeatedly to achieve results for the cause. They want Democrats to block must-pass bills until action is taken to protect dreamers, even after last month’s shutdown failed to achieve anything more than a commitment from McConnell to debate the issue on the Senate floor.

Rep. Luis V. Gutiérrez (D-Ill.) said his colleagues faced risks if they voted for the bill — in his words, “to deport dreamers.”

“You all know that on the progressive side of the Democratic Party, this is not going away,” said Gutierrez.

Several House Democrats emerged from the Thursday-night caucus meeting resolved to hold the line.

“I think there’s a very strong sentiment that this is a moment that we can’t let pass,” Rep. Daniel Kildee (D-Mich.) said. “We’ve allowed these moments to pass in the past. This is a moment we can’t let pass without doing everything we can to move forward on DACA.”

But others were unconvinced. Some were skittish over another shutdown, especially with Senate Democrats largely on board with the spending deal, and others simply thought the budget deal was too good to pass up.

Rep. Terri A. Sewell (D-Ala.) cited a pair of federal health programs that were extended as part of the deal, while Rep. Gerald E. Connolly (D-Va.) said he simply thought an extended shutdown would be counterproductive.

“I believe harm would have flowed toward dreamers had the government shut down,” he said. “What we saw last time was that public support actually fell. And it’s an awfully hard intellectual contortion to argue against a bill where we won pretty much every battle.”

Seventy-three House Democrats voted for the bill, while 119 voted against it. Among Republicans, 167 supported it and 67 voted no.

Republican leaders, who have typically emerged from spending battles facing questions about divisions in their own party, were more than pleased to observe the Democratic split.

“They had a bad strategy when they came up with this idea in December, and they have been fractured ever since,” said Rep. Patrick T. McHenry (R-N.C.), the GOP’s chief deputy whip. “To me, it’s a fascinating display of a bipartisan win and at the same time, Democrats ripping themselves apart about a bipartisan agreement. It doesn’t make any damn sense.”

But the spectacle in the Senate, prompted entirely by Paul, tempered any Republican glee.

Hours before the shutdown took effect, a visibly irritated McConnell tried to move to a vote, but Paul objected. Then Paul launched into a lengthy floor speech deriding bipartisan complicity on deficit spending while the country goes “on and on and on, finding new wars to fight that make no sense.” The senator direly predicted a “day of reckoning,” possibly in the form of the collapse of the stock market.

As the hours ticked on, Paul repeatedly refused to consent to allowing the vote to happen, as lawmakers and aides of both parties grew increasingly annoyed at him.

Sen. John Cornyn (R-Tex.), leaving the floor after an unsuccessful attempt to curtail Paul’s standoff, called the gambit “grossly irresponsible” and said that leaders would not entertain his demand for a vote.

“Why reward bad behavior?” Cornyn said.

Senate leaders remained confident all along that the spending deal would pass easily in the end, and it did. But without an agreement among all senators on timing, the voting was delayed until 1 a.m., when the time allotted for debate expired. By then, the government had been shut down for an hour.

Senators of both parties were left fuming, with most of their ire directed toward Paul.

“He has mastered the art of ticking off his colleagues,” said Sen. Christopher A. Coons (D-Del.).

“It’s a colossal waste of everybody’s time,” said Sen. John Thune (R-S.D.). Of Paul, Thune said, “He never gets a result.”

Paul himself made no apologies as he delivered one floor speech after another, casting himself as a lone defender of fiscal austerity, despite having voted in December for a tax bill that added at least $1 trillion to the debt.

House conservatives also objected to the enormous increase in federal spending, most of which would be piled onto the deficit with minimal attempts to offset it. But they were outweighed by Republicans eager to deliver the Pentagon funding that Trump had long demanded.

House Speaker Paul D. Ryan (R-Wis.) highlighted the military funding boost Thursday ahead of the vote and predicted the bill would pass on a bipartisan basis. “There is widespread agreement in both parties that we have cut the military too much, that our service members are suffering as a result, and that we need to do better,” he said.

The bill’s impact ranges far beyond the military — renewing several large health-care programs, suspending the national debt limit for a year and extending billions of dollars of expiring tax breaks. The cost of those provisions exceeds $560 billion, though lawmakers included some revenue-raising offsets.

In comparison, the 2009 fiscal stimulus bill passed at the bottom of a global recession under Obama was estimated to cost $787 billion over 10 years. Republicans were nearly unanimous in opposing that measure in their clamor for fiscal restraint in the face of growing deficits — demands largely drowned out now in the Trump era.

This spending bill, proposed amid an economic boom, could be the last major piece of legislation passed before November’s midterm elections, barring a breakthrough on the thorny immigration debate.

Under the deal, existing spending limits would be raised by a combined $296 billion through 2019. The caps were put in place in 2011 after a fiscal showdown between Obama and GOP congressional leaders who demanded spending austerity.

The agreement includes an additional $160 billion in uncapped funding for overseas military and State Department operations, continuing a costly line item that dates back to the immediate response to the 2001 terrorist attacks. And about $90 billion more would be spent on disaster aid for victims of recent hurricanes and wildfires. Tax provisions would add another $17 billion to the cost of the bill.

The spending is partially offset through an increase in customs and immigration fees, as well as sales from the Strategic Petroleum Reserve and other accounting maneuvers. Still, according to an analysis by the nonpartisan Committee for a Responsible Federal Budget, the package is set to add $320 billion to the budget deficit over the coming decade.

David Weigel, Ed O’Keefe, Damian Paletta and Sean Sullivan contributed to this report.