I am often inspired by Hawkeye from M.A.S.H. - if you do not know this character, it is a talented doctor drafted into the Korean War who overcame difficulties with humor. But from time to time he has moments where even he cannot crack a joke and goes very serious, even dark.
For First, like Hawkeye has a strict line which turns him from comedian into gloomy man, so your character should have. That might be the first parameter for your character. Define for him "when is enough" and make it part of his story. For example, your character might keep picking on some side-character but when it comes to action he has respect for him and would not ever joke or pick on side-character's professional skills. Or simply your Hero's brother was kidnapped and never returned and Hero, while being wise-cracking detective, takes cases about children with utmost serious attitude.
Second tool, I like to use to write funny but mature characters, as Mark mentioned - reaction to circumstance. Your character might be simply a kind person and when seeing sad kid crying over dropped ice-cream he will do some close-up magic trick and pull a dollar from kid's ear and give it to him despite knowing that was his last dollar.
Set boundaries of your character - not everything is a laughing matter and each of us have different taste in humor (pick the niche of the jokes - Puns, dad jokes, anecdotal, lips, wise-cracks, wordplay...)
Putting your character in a position where he can cheer somebody up - and he succeeds
Bonus: Realize you are master of your universe and you make things happen. Put some banana peels on the ground to create those light-hearted moments and let the protagonist take it positively instead of gleaming on people who laughed and challenging perpetrator to duel seeking satisfaction
Bonus 2 - Do not create jokes unless you are an experienced comedian. While from time to time you can succeed to make the reader chuckle, the safer way (in my opinion), is pick the joke up front and put the character in a situation where he can use it with full potential.
Bonus 3 - I wrote one character with a purpose to be super fun but instead he ends up being lame - I simply tried too hard and the jokes were forced and bad. My Beta-audience when they first met the character said "Dude that Hero2 is super cringy, you gotta change that". I made his badly written humor as part of his character and Beta-audience loved it. To quote: "I cannot wait what poop come from his mouth next time - it makes me laugh." My point is - even bad humor can be amusing.