This rhythm pattern seems very famous and is oftenly used to knock on someone's door, sometimes as a code:
Does it have an history? Where does it come from?
In music, the call "Shave and a Haircut" and the associated response "two bits" is a simple, 7-note musical couplet, riff or fanfare popularly used at the end of a musical performance, usually for comic effect. It is used both melodically and rhythmically, for example as a door knock. "Two bits" is an archaism in the United States for 25 cents, a quarter. "Six bits" is occasionally used. The final words may also be "get lost", "drop dead" (in Australia), or some other facetious expression... although words are now rarely used to accompany the rhythm or the tune.
An early occurrence of the tune is from an 1899 Charles Hale song, "At a Darktown Cakewalk". Other songs from the same period also used the tune. The same notes form the bridge in the "Hot Scotch Rag", written by H. A. Fischler in 1911.
The former prisoner of war and U.S. Navy seaman Doug Hegdahl reports fellow U.S. captives in the Vietnam War would authenticate a new prisoner's U.S. identity by using "Shave and a Haircut" as a shibboleth, tapping the first five notes against a cell wall and waiting for the appropriate response.
According to @Rodrigo (from a deleted answer)
In Mexico, people say "Chinga Tu Madre" followed by "Cabron." It's offensive in a comical way and is often used when people honk their automobile horns or whistle .
According to @PatDobson (from the comments)
This was used in great effect in the film Who framed Roger Rabbit to tempt the pesky rabbit from his hiding place in the speakeasy.
In the Netherlands a comical music group, called The Cocktail Trio, had a hit in 1965 with a song about a flea circus. Ultimately a flea makes the biggest jump ever to the moon. The song ends with the "Shave and a haircut... two bits" riff with the Dutch line "Die zien we nooit meer... terug" wich translates as "We'll never see him... again". Everybody in the Netherlands knows this text to the riff, even if they don't know the original song.
The music to the song was composed by Ad van der Gein and Hans Ninaber. The Cocktail Trio also recorded an instrumental version with the international title Tiddley Winks. I don't think the notes of "Shave and a haircut" were invented by them. To me it sounds like something more traditional.